3
votes

I have the following in mind:

  1. A product can have multiple categories
  2. A category can be in different products.
  3. A category has a parent (category) if it's not a general category (in that case the parent would be nil)

Thinking from a relational database point of view, this would be something that I would implement as:

  1. Table product
  2. Table product_category (as primary keys: product_id, category_id)
  3. Table category (with a parent_id referencing a category or nil if it's a "general" cateogry)

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?

1

1 Answers

7
votes

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