Rails - Parent/child relationships

bcoughlan picture bcoughlan · Feb 7, 2011 · Viewed 14.9k times · Source

I'm currently using a standard one-to-one relationship to handle parent/child relationships:

class Category < ActiveRecord::Base
  has_one :category
  belongs_to :category
end

Is there a recommended way to do it or is this ok?

Answer

Toby Hede picture Toby Hede · Feb 7, 2011

You will need to tweak the names you are using to get this working - you specify the name of the relationship, and then tell AR what the class is:

class Category < ActiveRecord::Base
  has_one :child, :class_name => "Category"
  belongs_to :parent, :class_name => "Category" 
end