向现有Rails模型添加模型引用
我想知道在Rails 3中添加两个现有类之间关系的“正确”方法。
鉴于现有的模型:小丑和兔子
我想添加一个从Rabbit到Clown的引用(belongs_to)。 我首先尝试生成迁移:
rails g migration AddClownToRabbits clown:reference
这给了我一个看起来像这样的迁移:
class AddClownToRabbits < ActiveRecord::Migration def self.up add_column :rabbits, :clown, :reference end def self.down remove_column :rabbits, :clown end end
在rake db:migrate
迁移之后,我检查SQLite3的development.db并看到一个新列: "clown" reference
我想我期待一个"clown_id" integer
列和一个看起来像这样的迁移:
class AddClownToRabbits < ActiveRecord::Migration def self.up add_column :rabbits, :clown_id end def self.down remove_column :rabbits, :clown_id end end
我敢肯定:引用应该等同于“t.references:clown”,但我找不到文档(大惊喜)。 API表示add_column: Instantiates a new column for the table. The type parameter is normally one of the migrations native types, which is one of the following: :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean.
Instantiates a new column for the table. The type parameter is normally one of the migrations native types, which is one of the following: :primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean.
……没有提及 :参考。
在Rabbit中设置belongs_to并在Clown中设置has_many之后,您可以使用以下命令进行迁移:
add_column :rabbit, :clown_id, :integer
如果您使用边缘导轨(4.0),您可以使用:
rails generate migration AddAddressRefToContacts address:references
正如你可以从文档中看到的那样。
我不确定你在哪里有这个想法,但是没有(也从来没有)这样的语法用add_column
做你想做的add_column
。 为了得到你想要的行为,你必须做t.refences :clown
,如你所说。 在后台,它将调用: @base.add_column(@table_name, "#{col}_id", :integer, options)
。
看到这里 。
编辑:
我想我可以看到你困惑的根源。 您看到方法调用t.reference
并假设它是一种数据类型,因为存在t.integer
和t.string
等调用,并且这些是数据类型。 那是错的。 引用不是数据类型,它只是方法的名称,类似于t.rename
。