Rails - How to access the attribute of nested parameters?
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 user_id to change it.
I tried params[:item][:user_items_attributes][0]and it does not work. I also tried params[:item][:user_items_attributes][0][:user_id]. What is the correct way to change user_id?
The value params[:item][:user_items_attributes]is the hash of the string for the hash. You are trying to access it using an integer 0instead '0':
params[:item][:user_items_attributes]['0']
=> {"user_id"=>"8"}
, , , - HashWithIndifferentAccess .
the best way to access user_id is
2.2.1 :122 > item_params = {
2.2.1 :123 > "name" => "",
2.2.1 :124 > "description" => "",
2.2.1 :125 > "tag_list" => "",
2.2.1 :126 > "user_items_attributes" => {"0" => {"user_id" => "8"}},
2.2.1 :127 > "created_by" => 8,
2.2.1 :128 > "status" => 0
2.2.1 :129?> }
=> {"name"=>"", "description"=>"", "tag_list"=>"", "user_items_attributes"=>{"0"=>{"user_id"=>"8"}}, "created_by"=>8, "status"=>0}
2.2.1 :130 > item_params['user_items_attributes']['0']['user_id']
=> "8"