尝试设置外键时SQLite3 :: SQLException?

时间:2012-01-29 10:35:02

标签: ruby-on-rails

我有三个模型:User,Micropost和Comment。我正在尝试按如下方式设置外键:

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

但是我收到了这个错误:

  

发生了错误,此操作和所有后​​续迁移都已取消:

     

SQLite3 :: SQLException:near“user_id”:语法错误: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 个答案:

答案 0 :(得分: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