请考虑以下关联:
class Product < ActiveRecord::Base belongs_to :shop accepts_nested_attributes_for :shop end如果
params[:product][:shop_attributes] = {"name" => "My Shop"}我愿意:
@product = Product.new(params[:product]) @product.save将按预期创建一个名为我的商店"的新商店并将其分配给@product.
a new shop with name "My Shop" is created and assigned to the @product, as expected.
但是,我不知道shop_attributes包含某些id时会发生什么,例如:
However, I can't figure out what happens when shop_attributes contains some id, like:
params[:product][:shop_attributes] = {"id" => "20", "name" => "My Shop"}我收到以下错误:
Couldn't find Shop with ID=20 for Product with ID=问题1
这是什么意思?
问题2
如果是这种情况,即商店的id是已知的,并且具有这样的id的商店已经存在,我应该如何创建@product以便将该商店分配给它? /p>
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 ?
推荐答案我认为您正在尝试创建一个新的关联项,而不是与一个现有项关联.
I think that you're trying to figure out creating a new associated item vs. associating with an existing item.
对于创建新项目,您似乎可以正常使用. 当您在shop_attributes中传递ID时,该ID不起作用,因为它正在查找尚不存在的关联.
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"这会将当前产品的商店分配给ID为"shop_id"的商店. (产品应具有"shop_id"列.)
This will assign the current product's shop to the shop with id 'shop_id'. (Product should have a 'shop_id' column.)
更多推荐
Rails 3:如何"accepts
发布评论