How to create table entry with multiple related categories?

Perhaps I should create a table row to hold an array of category ID’s?
There’s probably an easy standard way of doing this in RoR and I just
can’t wrap my brain around a practical way to do this right off.

I have a table that contains my product category names and another table
that contains my actual product names with other product specific

Each product needs to be assigned to multiple categories. It could be
just two or perhaps ten categories, the number varies.

I know how to create a has_many relationship for each category and I can
get a category pulldown menu to appear in a new product entry form that
works for assigning one category per product.

How should I approach being able to have multiple categories for each
product though? Should I create a table row in the products table for
each possible category? Or create say five rows so each product can have
up to five categories?

Eventually I’d like to offer users to ability to filter product search
results by selecting multiple category checkboxes.

Any recommendations appreciated.


I think has_and_belongs_to_many is what you are after. This setup
3 tables:


products_product_categories is defined as such (postgresql syntax):

create table products_product_categories(
product_id integer references products(id),
product_category_id integer references product_categories(id),
primary key (product_id, product_category_id)
)without oids;

This way products has_and_belongs_to_many product_categories and vice

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs