Search code examples
ruby-on-railsassociationsparent-child

Rails - Parent/child relationships


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?


Solution

  • 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