Topic: Help with HABTM and scoping

I'm having a heck of a time getting a HABTM working while scoping an udpate operation. What I'm doing is pretty basic so I'm sure I just don't know the "right" of way doing this. I've googled a lot and haven't had any luck finding reasonable documentation for this. Here is what I'm trying to do:

Products -> HABTM <- Categories

AND

Products -> Belongs To -> User

So users have many products.

When I try to update the product and assign it to a new category I'm getting a duplicate ID error like this:

Mysql::Error: Duplicate entry '44' for key 1: INSERT INTO categories_products (`product_id`, `category_id`, `id`) VALUES (13, 44, 44)

It looks from the error like it's forcing the ID column to something when it shouldn't, it should be using an auto increment value from the database.

Here is the controller code:

def update
    get_user # This method grabs the user from the session for the scoping operations
   
    @product_id = @user.products.find(params[:id]).id # this grabs the id and checks it against the scope of the user because the user can only edit their own products
   
    @product = Product.find(@product_id)
    @product.categories = Category.find(@params[:category][:category_ids])

    @product.update_attributes(params[:product])
~ some basic error handling stuff clipped ~

If someone has experience with this I'd appreciate any comments on the right way of doing this.

Re: Help with HABTM and scoping

A HABTM join table shouldn't have an "id" column. Try removing it. If you create it with migrations you would do it like this:

create_table :categories_products, :id => false do |t|
  t.column :category_id, :integer
  t.column :product_id, :integer
end

Railscasts - Free Ruby on Rails Screencasts

Re: Help with HABTM and scoping

You're a genius, that did it!!