Rails 3 - A model with a one to one relationship to itself - do I need belongs_to

廉价感情. 提交于 2019-12-12 11:44:16

问题


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'.


回答1:


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 :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.




回答2:


Yes, you would need that belongs_to since this is what will tell rails about this relationship.



来源:https://stackoverflow.com/questions/6749611/rails-3-a-model-with-a-one-to-one-relationship-to-itself-do-i-need-belongs-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!