Rails 3 - 与其自身具有一对一关系的模型 - 我需要belongs_to
我有一个名为 Person 的模型。它有两个属性 - name 和parent_person_id
一个人总是有一个父人。
我应该在模型中使用belongs_to吗?如果是的话,这样做有什么好处。
class Person < ActiveRecord::Base
belongs_to :person
end
我还没有尝试过这段代码,我正常的 mysql 方式似乎有点错误。
我在这里寻求意见比什么都重要,我对 Rails 还很陌生,并且想确保我做事正确,以“Rails 方式”做事。
I have a model named Person. It has two properties - name and parent_person_id
A person will always have a parent person.
Should I be using belongs_to in the model? If so, what are the advantages of doing so.
class Person < ActiveRecord::Base
belongs_to :person
end
I've not tried this code out yet, it seems a bit wrong my normal mysql ways.
I'm looking for opinions here more than anything, I'm quite new to the rails and want to make sure I'm doing things properly, doing things 'the Rails way'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议使用像 ancestry 这样的树结构。它为您提供关联以及许多实用方法(查找父级、子级、兄弟姐妹、检索子树)。
如果你不希望这样,那么你的belongs_to关联必须看起来像这样:
因为如果没有这个选项,rails会寻找person_id的外键,如果没有找到,
点燃你的CPU抛出错误消息。I'd suggest using a gem like ancestry for a tree structure like that. It gives you your association plus lots of utility methods (finding parent, children, siblings, retrieving a subtree).
If you don't want that, then in your belongs_to association has to look like this:
since without that option, rails would look for a foreign key of person_id and, not finding that,
light your CPU on firethrow an error message.是的,您需要 belongs_to 因为这将告诉 Rails 关于这种关系的信息。
Yes, you would need that belongs_to since this is what will tell rails about this relationship.