34

Consider the following association:

class Product < ActiveRecord::Base
  belongs_to :shop
  accepts_nested_attributes_for :shop
end

If

params[:product][:shop_attributes] = {"name" => "My Shop"}

and I do:

@product = Product.new(params[:product])
@product.save

a new shop with name "My Shop" is created and assigned to the @product, as expected.

However, I can't figure out what happens when shop_attributes contains some id, like:

params[:product][:shop_attributes] = {"id" => "20", "name" => "My Shop"}

I get the following error:

Couldn't find Shop with ID=20 for Product with ID=

Question 1

What does this means ?

Question 2

If this is the case, i.e. the id of the shop is known, and the shop with such id already exist, how should I create the @product such that this shop will be assigned to it ?

Chetan
  • 46,743
  • 31
  • 106
  • 145
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746

1 Answers1

14

I think that you're trying to figure out creating a new associated item vs. associating with an existing item.

For creating a new item, you seem to have it working. When you passed the id in shop_attributes, it did not work, because it's looking up an association that doesn't exist yet.

If you're trying to associate with an existing item, you should be using the following:

params[:product][:shop_id] = "20"

This will assign the current product's shop to the shop with id 'shop_id'. (Product should have a 'shop_id' column.)

clemensp
  • 2,525
  • 23
  • 21
  • 7
    Any idea how this works if a product has multiple shops? Like `params[:product][:shops_attributes] = {"0" => {"id" => "20", "name" => "My Shop"}, "1" => {...}}`? Thanks! – Cimm Jun 29 '11 at 13:52
  • 1
    Using the `params[:product][:shop_id]` methodology, you can do: `params[:product][:shop_ids] = [20,23,27]` – Michael Lynch Oct 11 '13 at 17:23