how can I do self-reference with ruby on rails?

JRafaelM picture JRafaelM · May 23, 2011 · Viewed 25.7k times · Source

I want to self-referentiate a model in a RoR app but, I don't know exactly how. I want to save a linked list where the next node has the id of the previous one. how can I do this rails way? It is a one-to-one relation.

Answer

Hck picture Hck · May 23, 2011

The easiest way:

class MyModel < ActiveRecord::Base
  belongs_to :parent, :class_name => 'MyModel'
  has_many :children, :class_name => 'MyModel', :foreign_key => 'parent_id'
end