问题
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