Rails 中has_one 和belongs_to 之间的区别?
我试图理解 RoR 中的 has_one
关系。
假设我有两个模型 - Person
和 Cell
:
class Person < ActiveRecord::Base
has_one :cell
end
class Cell < ActiveRecord::Base
belongs_to :person
end
我可以使用 has_one :person
而不是 belongs_to :person
> 在 Cell
模型中?
不是一样吗?
I am trying to understand has_one
relationship in RoR.
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
Can I just use has_one :person
instead of belongs_to :person
in Cell
model?
Isn't it the same?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,它们不可互换,并且存在一些真正的差异。
belongs_to
表示外键位于此类的表中。 所以belongs_to
只能进入保存外键的类。has_one
表示另一个表中有一个外键引用该类。 因此has_one
只能进入被另一个表中的列引用的类中。所以这是错误的:
这也是错误的:
正确的方法是(如果
Cell
包含person_id
字段):对于双向关联,您需要每种关联之一,他们必须进入正确的班级。 即使对于单向关联,使用哪一种关联也很重要。
No, they are not interchangable, and there are some real differences.
belongs_to
means that the foreign key is in the table for this class. Sobelongs_to
can ONLY go in the class that holds the foreign key.has_one
means that there is a foreign key in another table that references this class. Sohas_one
can ONLY go in a class that is referenced by a column in another table.So this is wrong:
And this is also wrong:
The correct way is (if
Cell
containsperson_id
field):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.
如果您添加“belongs_to”,那么您将获得双向关联。 这意味着您可以从细胞中获取一个人,并从该人中获取一个细胞。
没有真正的区别,两种方法(有和没有“belongs_to”)使用相同的数据库模式(单元格数据库表中的 person_id 字段)。
总结一下:不要添加“belongs_to”,除非您需要模型之间的双向关联。
If you add "belongs_to" then you got a bidirectional association. That means you can get a person from the cell and a cell from the person.
There's no real difference, both approaches (with and without "belongs_to") use the same database schema (a person_id field in the cells database table).
To summarize: Do not add "belongs_to" unless you need bidirectional associations between models.
使用两者可以让您从 Person 和 Cell 模型获取信息。
Using both allows you to get info from both Person and Cell models.