Rails - Parent/child relationships

I found that I had to make a minor change to @equivalent8's solution to make it work for Rails 5 (5.1.4):

class Category < ActiveRecord::Base
  has_many :children, :class_name => "Category", foreign_key: 'parent_id'
  belongs_to :parent, :class_name => "Category", foreign_key: 'parent_id', :optional => true
end

Without the foreign_key declaration, Rails tries to find the children by organization_id instead of parent_id and chokes.

Rails also chokes without the :optional => true declaration on the belongs_to association since belongs_to requires an instance to be assigned by default in Rails 5. In this case, you would have to assign an infinite number of parents.


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