如何在Rails中访问嵌套参数

在Controller中,我正在尝试访问深度嵌套的参数。 这是我的参数跟踪。

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]和其他变种。 什么是正确的styntax?

如果重要,

Inventory has_many :ingredients
Inventory accepts_nested_attributes_for :inventories

谢谢!

直接访问值“面包”将字面上是:

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

我打赌你不想这样做。

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

 @inventory = Inventory.new(params[:inventory]) # or @inventory.attributes = params[:inventory] for an existing # inventory instance ingredient = @inventory.ingredients.first ingredient.ingredient_name # => "Bread"