Mel*_*emi 27 migration ruby-on-rails
我想知道在Rails 3中添加两个现有类之间关系的"正确"方法.
鉴于现有型号:小丑和兔子
我想添加一个从Rabbit到Clown的引用(belongs_to).我首先尝试生成迁移:
rails g migration AddClownToRabbits clown:reference
Run Code Online (Sandbox Code Playgroud)
这给了我一个看起来像这样的迁移:
class AddClownToRabbits < ActiveRecord::Migration
def self.up
add_column :rabbits, :clown, :reference
end
def self.down
remove_column :rabbits, :clown
end
end
Run Code Online (Sandbox Code Playgroud)
完成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
Run Code Online (Sandbox Code Playgroud)
我敢肯定:引用应该等同于"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.
......没有提及:参考.
Pau*_*lgo 57
如果您使用边缘导轨(4.0),您可以使用:
rails generate migration AddAddressRefToContacts address:references
Run Code Online (Sandbox Code Playgroud)
正如你可以从文档中看到的那样.
cle*_*nsp 19
在Rabbit中设置belongs_to并在Clown中设置has_many之后,您可以使用以下命令进行迁移:
add_column :rabbit, :clown_id, :integer
Run Code Online (Sandbox Code Playgroud)