Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 350
Finnnn Avatar asked Jan 19 '23 04:01

Finnnn


1 Answers

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.

like image 157
Thilo Avatar answered Jan 21 '23 17:01

Thilo