2012-01-29 92 views
0

我有三種模型:User,Micropost和Comment。我正在嘗試設置外鍵如下:嘗試設置外鍵時SQLite3 :: SQLException?

class CreateComments < ActiveRecord::Migration 
    def change 
    create_table :comments do |t| 
     t.text :content 

     t.timestamps 
    end 

    add_index :comments, :micropost_id, :user_id 
    end 
end 

但我得到這個錯誤:

An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: near "user_id": syntax error: CREATE user_id INDEX "index_comments_on_micropost_id" ON "comments" ("micropost_id")

我明白Rails的插入基於模型belongs_tohas_many聲明外鍵。但是,我所擁有的一切設置:

comment.rb:

class Comment < ActiveRecord::Base 
    belongs_to :micropost 
    belongs_to :user 
end 

micropost.rb:

class Micropost < ActiveRecord::Base 
    attr_accessible :title, :content 

    belongs_to :user 
    has_many :comments 
end 

user.rb:

class User < ActiveRecord::Base 
    # Include default devise modules. Others available are: 
    # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :email, :password, :password_confirmation, :remember_me 

    has_many :microposts 
    has_many :comments 
end 

任何建議來解決這個問題?

回答

1

如果要在2列上創建索引,則語法爲add_index table_name, [column1_name, column2_name], options。您還需要定義表中的列(當您在模型類中添加belongs_to時,ActiveRecord不會自動添加它們)。所以你的移民應該是

class CreateComments < ActiveRecord::Migration 
    def change 
    create_table :comments do |t| 
     t.text :content 
     t.integer :micropost_id 
     t.integer :user_id 

     t.timestamps 
    end 

    add_index :comments, [:micropost_id, :user_id] 
    end 
end