可以将列添加到作为外键的ActiveRecord模型中吗?

时间:2013-08-26 08:45:31

标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-4 rails-activerecord

我可以在Rails中轻松创建一个脚手架或模型,其中一个字段是另一个模型的引用(外键):

rails g model Cat owner:references
rails g scaffold Cat owner:references

但我似乎无法在迁移中添加列:

rails g migration AddOwnerToCats owner:references

以上操作产生的迁移文件如下:

class AddOwnerToCats < ActiveRecord::Migration
  def change
    add_column :cats, :owner, :references
  end
end

当我尝试使用rake db:migrate运行它时,我明白了:

SQLite3::SQLException: near "references": syntax error: ALTER TABLE "cats" ADD "owner" references

那么有没有办法添加一个引用另一个模型的列?或者我必须这样做:

rails g migration AddOwnerToCats owner_id:integer

然后进入迁移并添加owner_id的索引?

2 个答案:

答案 0 :(得分:0)

我能想到的一种解决方法是简单地创建列,并在模型中给出连接条件。即。

has_many :x, :class_name => y, :foreign_key => z

答案 1 :(得分:0)

我知道这是一个老问题,但是从Rails 5(可能是早期版本)开始,official docs已经更新:

rails generate migration AddOwnerRefToCats owner:references

将生成

class AddOwnerRefToCats < ActiveRecord::Migration[5.0]
  def change
    add_reference :cats, :owner, foreign_key: true
  end
end

您还可以添加, index: true来创建索引。