Rails 3:如何"accepts

编程入门 行业动态 更新时间:2024-10-27 10:20:38
本文介绍了Rails 3:如何"accepts_nested_attributes_for"工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

请考虑以下关联:

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

本文发布于:2023-10-18 03:06:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502894.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Rails   quot   accepts

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!