Rails 3 - one-to-one model - I need to belong_to

I have a model called Person. It has two properties - name and parent_person_id

A person will always have a parent.

Should I use belongs_to in the model? If so, what are the benefits of this.

class Person < ActiveRecord::Base belongs_to :person end 

I have not tried this code yet, it seems that these are my wrong normal mysql methods.

I am looking for opinions here more than anything, I am completely new to rails and want me to do everything right by doing things "Rails way".

+4
source share
2 answers

I would suggest using a gem like ancestry for such a tree structure. This gives you your association, as well as many useful methods (finding a parent, children, brothers and sisters, getting a subtree).

If you don't want this, then your belongs_to association should look like this:

 belongs_to :person, :foreign_key => "parent_person_id" 

since without this option the rails will look for the foreign key person_id and, without detecting this, will start your processor in fire mode .

+9
source

Yes, you will need to_to , as this is what the rails will say about this relationship.

0
source

All Articles