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?
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?
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:
I found that I had to make a minor change to @equivalent8's solution to make it work for Rails 5 (5.1.4):
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.has_many version:
Since the relation is symmetric, I actually find that different than what Toby wrote, that I prefer the following:
For some reason "has one parent, many children" is the way my mind things, not "has many parents, only one child"