Rails 3: How does "accepts_nested_attributes_for" work?

Misha Moroshko picture Misha Moroshko · Dec 19, 2010 · Viewed 26.1k times · Source

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 ?

Answer

clemensp picture clemensp · Dec 20, 2010

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.)