I have a category model, which is basically what products will be assigned to.
So my category model looks like this:
attr_accessible :name
has_many :category_products do
def with_products
includes(:product)
end
end
has_many :products, :through => :category_products
What I would like to do is to have categories within categories – so a product should be able to be put in Men and then Shoes.
That way, I can have a Men drop-down menu, that produces all the subcategories within Men like Shoes.
But, if a user clicks on Men they will see all the products in that category.
Thoughts?
You can use a gem like Ancestry to organize your categories into a hierarchy.
If you only need one level deep of nesting, you can use a self-join.
You’ll also need a migration to add
category_idto yourcategorytable.Stick a drop down in your
app/views/categories/_form.html.erbforcategory_idand populate it with your list of Categories. You can use this to select a “Parent” for your categories.Then you can do stuff like:
Using a gem like Ancestry will give you a lot more flexibility when it comes to working with these categories and their associations though.
A bit about how Ancestry works: