How to access nested parameters in Rails

╄→尐↘猪︶ㄣ 提交于 2019-12-12 01:09:20

问题


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"}

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

If it matters,

Inventory has_many :ingredients
Inventory accepts_nested_attributes_for :inventories

Thanks!


回答1:


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.

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"


来源:https://stackoverflow.com/questions/16073617/how-to-access-nested-parameters-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!