简体   繁体   English

Rails 3 - 与自身具有一对一关系的 model - 我需要belongs_to

[英]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.

相关问题 Rails:如何创建具有两个“ belongs_to”关系的模型,其中一个始终为空? - Rails: How do I create a model with two “belongs_to” relations, one of which is always empty? ActiveRecord:我是否需要belongs_to和has_one - ActiveRecord: Do I need both belongs_to and has_one Rails-从具有has_many和belongs_to关系的不同模型中查询一个模型 - Rails - Query One Model from within a Different Model with a has_many & belongs_to relationship Rails如何知道has_one / belongs_to关系是否存在 - Rails how to know if a has_one/belongs_to relationship exists 在Rails 4中has_one belongs_to关系问题 - has_one belongs_to relationship issue in Rails 4 使用has_many和belongs_to关系,我需要在一个索引视图中显示每个资源的参数 - Using a has_many and belongs_to relationship, I need to display the parameters of each resource in one index view 在Rails模型中,我可以将belongs_to更改为has_one并将has_one更改为belongs_to吗? - In Rails models, can I change belongs_to to has_one and has_one to belongs_to? rails belongs_to has_one。 需要一些解释 - rails belongs_to has_one. need some explanation Rails - 模型belongs_to和has_one相同的类 - Rails - model belongs_to and has_one same class Rails:has_one 和 belongs_to 相同 model - Rails : has_one and belongs_to same model
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM