简体   繁体   中英

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM