"Has many through" relations - Product - Category - Subcategory

333 Views Asked by At

I want to extend my current model scheme with a subcategory model.

Right now they look like this:

class Article < ActiveRecord::Base

    has_many :categorizations
    has_many :categories, :through => :categorizations

    ...
end



class Category < ActiveRecord::Base

    has_many :categorizations
    has_many :articles, :through => :categorizations

  ...
end



class Categorization < ActiveRecord::Base
    belongs_to :article
    belongs_to :category
end

I'm having a hard time wrapping my head around the next step.
Guess I've been looking at the problem for a bit too long.

Article has many Categories
Article has many SubCategories

Category has many Articles
Category has many Subcategories

Subcategory has many Articles
Subcategory has many Categories

1

There are 1 best solutions below

0
On BEST ANSWER

for category and subcategory you should use gem ancestry and create something like:

class Category < ActiveRecord::Base

    has_many :categorizations
    has_many :articles, :through => :categorizations

    has_ancestry
 end

here is documentatin: https://github.com/stefankroes/ancestry