"", "description" => "", "tag_list" => "", "user_i...">

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?

+4
source share
4 answers

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 .

+9

Ruby 2.3.0 Hash#dig, , Hash#[]. .

:

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

This is pretty easy to solve!

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

So, if you just want to get user_id:

params["user_items_attributes"]["0"]["user_id"] #=> "8"
+2
source

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" 
0
source

Source: https://habr.com/ru/post/1628854/


All Articles