user4584963
user4584963

Reputation: 2533

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?

Upvotes: 5

Views: 9847

Answers (4)

Philipp Meissner
Philipp Meissner

Reputation: 5482

That's quite easy to solve!

params["user_items_attributes"] #=> {"0" => {"user_id" => "8" }}

So if you want to just get the user_id:

params["user_items_attributes"]["0"]["user_id"] #=> "8"

Upvotes: 3

Anoob K Bava
Anoob K Bava

Reputation: 605

the best way to access the 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" 

Upvotes: 0

FixerRB
FixerRB

Reputation: 326

Starting from Ruby 2.3.0 you can use Hash#dig method which is safer than accessing with Hash#[]. You can find some useful examples here.

In your case it will look like:

user_id = item_params.dig("user_items_attributes", "0", "user_id")

Upvotes: 7

Shadwell
Shadwell

Reputation: 34784

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.

Upvotes: 12

Related Questions