向现有 Rails 模型添加模型引用 [英] Adding a Model Reference to existing Rails model
问题描述
我想知道在 Rails 3 中添加两个现有类之间关系的正确"方法.
I'd like to know the "proper" way to approach adding a relation between two existing classes in Rails 3.
鉴于现有模型:小丑和兔子
Given existing models: Clown & Rabbit
我想添加一个从 Rabbit 到 Clown 的引用 (belongs_to).我首先尝试生成迁移:
I'd like to add a reference (belongs_to) from Rabbit to Clown. I start by trying to generate a migration:
rails g migration AddClownToRabbits clown:reference
这给了我一个看起来像这样的迁移:
which gives me a migration that looks like:
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 并看到一个新列:小丑"参考
After rake db:migrate
on this migration I examine SQLite3's development.db and see a new column: "clown" reference
我想我期待一个 "clown_id" 整数
列和一个看起来像这样的迁移:
I guess I was expecting a "clown_id" integer
column and a migration that looked like:
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, :二进制,:boolean.
I'm sure :reference is supposed to be equivalent to "t.references :clown" but I can't find the documentation (big surprise). API says 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.
...没有 reference 到 :reference.
...with no reference to :reference.
推荐答案
在 Rabbit 中设置belongs_to,在Clown 中设置has_many 后,您可以进行迁移:
After you set belongs_to in Rabbit, and has_many in Clown, you can do a migration with:
add_column :rabbit, :clown_id, :integer
请参阅 Paulo's answer below 以获得更新的答案(Rails 4+)
See Paulo's answer below for a more updated answer (Rails 4+)
这篇关于向现有 Rails 模型添加模型引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!