问题
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 :ingredientsInventory 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