ruby - How to access nested parameters in Rails -


in controller, i'm trying access parameter nested. here 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 retrieve "bread" this. tried params[:inventory][:ingredient][:ingredient_name] , other variations. correct styntax?

if matters,

inventory has_many :ingredients
inventory accepts_nested_attributes_for :inventories

thanks!

direct access value "bread" literally be:

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

i bet don't want that.

with accepts_nested_attributes_for , hash structure, (also assuming ingredient attributes set correctly), can set params on inventory instance , value "bread" set ingredient_name attribute 1 of ingredient objects in association:

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

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -