如何在Rails中访问嵌套参数 [英] How to access nested parameters in Rails

查看:91
本文介绍了如何在Rails中访问嵌套参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在控制器中,我试图访问深度嵌套的参数.这是我的参数跟踪.

In a Controller, I'm trying to access a parameter which is deeply nested. Here is my parameter trace.

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"2j+Nh5C7jPkNOsQnWoA0wtG/vWxLMpyKt6aiC2UmxgY=",
 "inventory"=>{"ingredients_attributes"=>{"0"=>{"ingredient_name"=>"Bread"}},
 "purchase_date"=>"11",
 "purchase_price"=>"11",
 "quantity_bought"=>"11"},
 "commit"=>"Create Inventory"}

我正在尝试从中检索面包".我尝试了params[:inventory][:ingredient][:ingredient_name]和其他变体.正确的语法是什么?

I'm trying to retrieve "Bread" from this. I tried params[:inventory][:ingredient][:ingredient_name] and other variations. What is the correct styntax?

如果有关系,

Inventory has_many :ingredients
Inventory accepts_nested_attributes_for :inventories

谢谢!

推荐答案

直接访问值面包"将是:

Direct access to the value "Bread" would literally be:

params[:inventory][:ingredients_attributes]["0"][:ingredient_name]

我敢打赌你不想那样做.

I bet you don't want to do that.

使用accepts_nested_attributes_for和该哈希结构(还假设正确设置了成分属性),您可以在库存实例上设置参数,并且将值"Bread"设置为成分之一的Ingredient_name属性关联中的对象:

With accepts_nested_attributes_for and that hash structure, (also assuming the ingredient attributes are set up correctly), you can set the params on an inventory instance and the value "Bread" would be set as the ingredient_name attribute one of the ingredient objects in the association:

@inventory = Inventory.new(params[:inventory]) 
# or @inventory.attributes = params[:inventory] for an existing 
# inventory instance

ingredient = @inventory.ingredients.first
ingredient.ingredient_name
# => "Bread"

这篇关于如何在Rails中访问嵌套参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆