Has_and_belongs_to_many question

Hi,
ive got 3 tables Products, Categories and products_categories. The
relationship between products and categories tables is
has_and_belongs_to_many. This is working fine. But I have to find out
how to add and remove relationships to/from the products_categories
table.

For example, a new product is added and it needs to be put in a category
of choice. Or a product is obsolete and is remove from its current
category.

Can I get some help here?

Thanks

Petr

Hi Petr,

I had the same problem yesterday and found this. It worked brilliantly
for me.

http://jrhicks.net/Projects/rails/has_many_and_belongs_to_many.pdf

Hi and thanks,

But Im not sure how this will work for me. I just tried playing with a
bit and unsuccessfully.

Let me give you a better example.

Theres a products table with products 1-100 in it. Theres a category
table with categories 1-10 in it. Then theres products_categores table
that has columns product_id and category_id in it. It works fine if I
manually (via SQL) add something like product_id = 100 and category_id =
4. But How do I create or destroy such relationship in RoR and with
has_and_belongs_to_many?

Petr

I made a progress. I can now add relationships with

if product.save
category = Category.find(params[:objectid])
product.categories << category
end

but how do I destroy them?

Cool!

Updating the Product.categories (which comes from the
:has_and_belongs_to_many relationship) should do the trick (it does for
me).

For example in your controller you have (in short):

def update_product
@product = Product.find(@params[:id])
@product.categories = Category.find(@params[:category_ids])
@product.update_attributes(@params[:product])
end

For reading a few other things regarding this problem, the secret is in
the [] of name=“category_ids[]” (in the checkbox field as shown on the
document for example).

So that should update your join table if you untick a checkbox for
example.
Also if you destroy a Product, then all references to the product_id
should disappear (I’ve tried it and it worked).

By the way, is your join table really called products_categories?

If so then it’s not following Rails convention which is alphabetical
order. I think you can use an option to the :has_and_belongs_to_many if
you want to use a different name but I would recommend going the
conventional way :).