Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: How does "accepts_nested_attributes_for" work?

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 ?

like image 562
Misha Moroshko Avatar asked Dec 19 '10 22:12

Misha Moroshko


People also ask

What does Accepts_nested_attributes_for do in Rails?

accepts_nested_attributes_for is a really powerful method in Rails because it allows a model to alter related models through itself.

What are nested attributes rails?

Nested Attributes is a feature that allows you to save attributes of a record through its associated parent.


1 Answers

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

like image 129
clemensp Avatar answered Sep 29 '22 09:09

clemensp