Rails中has_one和belongs_to的区别? [英] Difference between has_one and belongs_to in Rails?
问题描述
我正在尝试了解 RoR 中的 has_one
关系.
I am trying to understand has_one
relationship in RoR.
假设我有两个模型 - Person
和 Cell
:
Let's say I have two models - Person
and Cell
:
class Person < ActiveRecord::Base
has_one :cell
end
class Cell < ActiveRecord::Base
belongs_to :person
end
我可以在 Cell
模型中使用 has_one :person
而不是 belongs_to :person
吗?
Can I just use has_one :person
instead of belongs_to :person
in Cell
model?
不一样吗?
推荐答案
不,它们不可互换,并且存在一些实际差异.
No, they are not interchangable, and there are some real differences.
belongs_to
表示外键在该类的表中.所以 belongs_to
只能进入持有外键的类.
belongs_to
means that the foreign key is in the table for this class. So belongs_to
can ONLY go in the class that holds the foreign key.
has_one
表示另一个表中存在引用此类的外键.所以 has_one
只能进入另一个表中的列引用的类.
has_one
means that there is a foreign key in another table that references this class. So has_one
can ONLY go in a class that is referenced by a column in another table.
所以这是错误的:
class Person < ActiveRecord::Base
has_one :cell # the cell table has a person_id
end
class Cell < ActiveRecord::Base
has_one :person # the person table has a cell_id
end
这也是错误的:
class Person < ActiveRecord::Base
belongs_to :cell # the person table has a cell_id
end
class Cell < ActiveRecord::Base
belongs_to :person # the cell table has a person_id
end
正确的方法是(如果 Cell
包含 person_id
字段):
The correct way is (if Cell
contains person_id
field):
class Person < ActiveRecord::Base
has_one :cell # the person table does not have 'joining' info
end
class Cell < ActiveRecord::Base
belongs_to :person # the cell table has a person_id
end
对于双向关联,您需要每个关联一个,并且他们必须进入正确的班级.即使是单向关联,使用哪一种也很重要.
For a two-way association, you need one of each, and they have to go in the right class. Even for a one-way association, it matters which one you use.
这篇关于Rails中has_one和belongs_to的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!