我想知道在Rails 3中添加两个已存在类之间关系的“正确”方法。
给定现有模型:Clown 和 Rabbit
我想要从 Rabbit 添加一个引用(belongs_to)到 Clown。我会尝试生成一个迁移文件来实现:
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
我相信:reference应该等同于"t.references :clown",但我找不到文档(大惊小怪)。API说add_column:为表格实例化一个新列。type参数通常是迁移原生类型之一,它是以下类型之一::primary_key、:string、:text、:integer、:float、:decimal、:datetime、:timestamp、:time、:date、:binary、:boolean。
...没有提及对:reference的引用。