Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - How do you access nested params attribute?

I have

item_params = {
  "name" => "",
  "description" => "",
  "tag_list" => "",
  "user_items_attributes" => {"0" => {"user_id" => "8"}},
  "created_by" => 8,
  "status" => 0
}

and I want to access the user_id to change it.

I tried params[:item][:user_items_attributes][0] and it doesn't work. I also tried params[:item][:user_items_attributes][0][:user_id]. What is the correct way to change the user_id?

like image 843
user4584963 Avatar asked Feb 15 '16 14:02

user4584963


Video Answer


1 Answers

The value of params[:item][:user_items_attributes] is a hash mapping a string to a hash. You're trying to access it using an integer 0 instead of '0':

params[:item][:user_items_attributes]['0']
 => {"user_id"=>"8"}

You can often access hashes using symbol keys rather than the string keys that will display if you inspect the hash because of rails' HashWithIndifferentAccess but you'll need to use a string for the key in this case.

like image 188
Shadwell Avatar answered Oct 05 '22 22:10

Shadwell