I have the following in mind:
Thinking from a relational database point of view, this would be something that I would implement as:
Thinking from a Rails modelling point of view, I have the following (I avoid writing the fields that don't really matter for this relation/hierarchical problem I'm dealing):
class Product < ActiveRecord::Base
...
has_many :categories
class Category < ActiveRecord::Base
...
Here comes de doubt: How do I specify the parent_id?
Is there any way to specify that a Category has one, and just one parent ID which references to another Category?
Something like this is fairly typical:
class Product < ActiveRecord::Base
has_many :categories, :through => :products_categories
# A has_and_belongs_to_many association would also be fine here if you
# don't need to assign attributes to or perform any operations on the
# relationship record itself.
end
class Category < ActiveRecord::Base
has_many :products, :through => :products_categories
belongs_to :category
has_many :categories # Optional; useful if this is a parent and you want
end # to be able to list its children.
Alternatively you could give these last two different names, e.g.:
belongs_to :parent, :class_name => :category
has_many :children, :class_name => :category
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With