Ruby-on-rails 如何访问嵌套参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2610263/
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
How to access nested params
提问by Flexo
I would like to get some nested params. I have an Order that has many Items and these Items each have a Type. i would like to get the type_id parameter from the controllers create method.
我想得到一些嵌套的参数。我有一个包含许多项目的订单,这些项目每个都有一个类型。我想从控制器创建方法中获取 type_id 参数。
@order = Order.new(params[:order])
@order.items.each do |f|
f.item_type_id = Item_type.find_by_name(f.item_type_id).id
end
The reason is that i want the user to be able to create new item_types in the view. When they do that i use an AJAX call add them to the db. When they post the form i get names of the item_type in the item_type_id parameter and i want to find the correct item_type and set the id to that
原因是我希望用户能够在视图中创建新的 item_types。当他们这样做时,我使用 AJAX 调用将它们添加到数据库中。当他们发布表单时,我在 item_type_id 参数中获取 item_type 的名称,我想找到正确的 item_type 并将 id 设置为
回答by Harish Shetty
To access the nested fields from paramsdo the following:
要访问嵌套字段,params请执行以下操作:
params[:order][:items_attributes].values.each do |item|
item[:type_id]
end if params[:order] and params[:order][:items_attributes]
Above solution will work ONLY if you have declared the correct associations and accepts_nested_attributes_for.
仅当您声明了正确的关联和accepts_nested_attributes_for.
class Order < ActiveRecord::Base
has_many :items
accepts_nested_attributes_for :items, :allow_destroy => true
end
class Item < ActiveRecord::Base
belongs_to :order
end

