0

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

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

2 Comments

I wanted to do your suggested correction, but I had a concern. I'm writing this code in my create action. Will ingredient = @inventory.ingredients.first work if I haven't saved @inventory yet?
Yes, it will work within the request after setting the attributes on the inventory instance, but it won't be persisted unless you successfully call @inventory.save.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.