Ruby-on-rails Rails 3:“accepts_nested_attributes_for”如何工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4485507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:56:17  来源:igfitidea点击:

Rails 3: How does "accepts_nested_attributes_for" work?

ruby-on-railsruby-on-rails-3nested-attributes

提问by Misha Moroshko

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.

@product正如预期的那样,一个名为“My Shop”的新商店被创建并分配给。

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

但是,我无法弄清楚当shop_attributescontains some时会发生什么id,例如:

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

问题 1

What does this means ?

这是什么意思?

Question 2

问题2

If this is the case, i.e. the idof the shop is known, and the shop with such idalready exist, how should I create the @productsuch that this shop will be assigned to it ?

如果是这种情况,即id商店的名字是已知的,并且id已经存在这样的商店,我应该如何创建@product这样的商店将被分配给它?

采纳答案by clemensp

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.

对于创建新项目,您似乎可以正常工作。当您在 shop_attributes 中传递 id 时,它不起作用,因为它正在查找尚不存在的关联。

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

这会将当前产品的商店分配给 ID 为“shop_id”的商店。(产品应该有一个“shop_id”列。)