Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails hierarchical modelling - Multiple categories

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?

like image 665
Nobita Avatar asked Dec 01 '25 13:12

Nobita


1 Answers

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
like image 169
Jordan Running Avatar answered Dec 04 '25 04:12

Jordan Running



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!