[英]Rails 3 - A model with a one to one relationship to itself - do I need belongs_to
I have a model named Person.我有一个名为 Person 的 model。 It has two properties - name and parent_person_id
它有两个属性 - name 和 parent_person_id
A person will always have a parent person.一个人总会有一个父母。
Should I be using belongs_to in the model?我应该在 model 中使用 belongs_to 吗? 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.我还没有尝试过这段代码,我的正常 mysql 方式似乎有点不对劲。
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'.我在这里寻找意见比什么都重要,我对 Rails 很陌生,想确保我做事正确,以“Rails 方式”做事。
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:如果您不希望这样,那么在您的 belongs_to 关联中必须如下所示:
belongs_to :person, :foreign_key => "parent_person_id"
since without that option, rails would look for a foreign key of person_id and, not finding that,
light your CPU on fire
throw an error message.因为没有这个选项,rails 会寻找 person_id 的外键,如果没有找到,就会
点燃你的 CPU 并
抛出错误消息。
Yes, you would need that belongs_to since this is what will tell rails about this relationship.是的,您将需要belongs_to ,因为这将告诉 rails 这种关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.