Self referential Models

If I have a Person model, and every person has a parent, that is in
fact another person, can I still use the belongs_to and has_many

A simple database migration might look like this

  t.column :name, :string
  t.column :parent, :integer

So every person only has a name and some people have parents.

I have written some methods that find a person’s parent and children:

class Person < ActiveRecord::Base
def find_children

def find_parent

These seem to work fine, but I was wondering if there was a neater way
to do this?



if you don’t need multiple parents per child (i.e, a parent has a lot of
kids, and each kid has one parent) then this should be perfect for you:

no need for two tables; it is self-referential in the sense that it
points back to the same table (=model) via a parent_id column.

some other good pointers while you’re at it:

acts_as_tree (the above link)
acts_as_nested_set (for getting a whole bunch of kids in one query,
instead of recursive calls)

this is a real self-referential model usage;
has_many :through - Self-referential has_many :through associations :

just general knowledge, the best place to use this is for friendships
(where X can be a friend of Y, without Y being a friend of X, as they
are all “friends”)

anyway… i hope the above helps.
good luck digging :slight_smile:

Thanks for this Shai,

acts_as_tree is exactly what I was looking for. I might also use
acts_as_list also.

Thanks for the other links too … I’m sure they will make some
interesting and useful reading.