0

I'm getting confused with the creation of a new link in a has_and_belongs_to_many table.

I think my use of the .build(...) is not correct but I can't find a way to fix it.

I wrote :

@user = User.find(1)
if (params[:product_id])
  @user.products.build(params[:product_id])
end
logger.debug "product id is  #{params[:product_id]}"

respond_to do |format|
  if @user.save
        ...

And the saved relationship in my table products_users is auto-incrementing ??? Example of the content of my table : (user_id ; product_id) = { (1;16) (1;17) (1;18) ...}

And it create blanck lines in the products table with these new id ... ? Is it a cause of build ?

But in the logger, I saw the correct value of :params[:product_id]... so what did I forgot ? :-s

The model is :

class User < ActiveRecord::Base
  has_and_belongs_to_many :products
end
class Product < ActiveRecord::Base
  belongs_to :group
  has_and_belongs_to_many :authors
  has_and_belongs_to_many :users
end
Stéphane V
  • 1,094
  • 2
  • 11
  • 25

2 Answers2

0

Instead of using

@user.products.build(params[:product_id])

try

@user.product_ids << params[:product_id]

I think that may do the trick for you.

KenB
  • 6,587
  • 2
  • 35
  • 31
  • I did indeed something comparable. Here is what worked for me :@user = User.find(1) if (params[:product_id]) @product = Product.find(params[:product_id]) unless @user.products.include?(@product) @user.products << @product end end – Stéphane V Jun 23 '11 at 08:37
-1

This is what worked for me

@user = User.find(1)                                                                                                                        
if (params[:product_id])
  @product = Product.find(params[:product_id])
  unless @user.products.include?(@product)
    @user.products << @product                                                                                                      
  end
end
Stéphane V
  • 1,094
  • 2
  • 11
  • 25
  • That looks like more code than you need; you don't have to instantiate @product here. Maybe try something like @user.product_ids << params[:product_id] unless @user.product_ids.include?(params[:product_id]) – KenB Jun 23 '11 at 12:50