Aniket Tiwari
Aniket Tiwari

Reputation: 3998

What is the best way to modify params nested hash?

What is the best way to modify some values in the params hash? For example, this is params hash.

{"utf8"=>"✓", "authenticity_token"=>"asdasdasd/Wi71c4U3aXasdasdasdpbyMZLYo1sAAmssscQEkv0WsWBDyslcWJxUZ2pPKOQFmJoVZw==", "user_api"=>{"user"=>"asdak", "name"=>"asdada", "friends_attributes"=>{"1566720653776"=>{"_destroy"=>"false", "player_name"=>"asda", "player_type"=>"backside", "user_interest"=>"cricket,football,basketball"}, "1566720658089"=>{"_destroy"=>"false", "player_name"=>"asdad", "player_type"=>"forward", "user_interest"=>"table_tennis,chess"}}}, "commit"=>"Save User Data"}

So from the above params, I need to modify user_options value to an array.

params.each do |key, user_api_hash|
    if key == "user_api"
      user_api_hash.each do |key, friend_hash|
        if key == "friends_attributes"
          friend_hash.each do |key, value|
            value["user_interest"] = value["user_interest"].split(',')
          end
        end
      end
    end
  end

I find this approach a bit un-efficient because I would have to iterate exponential times, depending on the number of hash. Can anyone suggest me a better way to do this?

Thank you in advance for your help.

Upvotes: 1

Views: 131

Answers (1)

Sebastián Palma
Sebastián Palma

Reputation: 33420

If you want to modify them rather than returning a new object:

(params.dig(:user_api, :friends_attributes) || []).each do |_, attributes|
  attributes['user_interest'] = attributes['user_interest'].split(',')
end
  • dig can access to the keys inside hash and inside other hashes inside them.
  • If some key doesn't exist, then it's going to return nil, in that case use an empty array, which will iterate 0 times.
  • Inside the user attributes, you can modify them with a simple assignation.

Upvotes: 3

Related Questions