Ruby-on-Rails [SOLVED]: Rails/ruby: how to retrieve hash key with unknown id

Ruby-on-Rails [SOLVED]: Rails/ruby: how to retrieve hash key with unknown id

Home Forums Frameworks Ruby on Rails Tutorials Ruby-on-Rails [SOLVED]: Rails/ruby: how to retrieve hash key with unknown id

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #246770

    Cloudy Point
    Keymaster

    QuestionQuestion

    I would like to check if there is button_attributes in my parameters. However, there is a random id for the array so I can’t verify if button_attributesis present or not.

    Here is the parameters:

    {"utf8"=>"?",
     "authenticity_token"=>"XsZyQxt0JcV/bD3joM+B0gHMu+GUf1FPcCpWltXGRa9ROs5ei8iG4EgkLz/thogng1cafWVg+5bYAcJulTGdsQ==",
     "letter"=>
      {"campaign_name"=>"",
       "scheduled_at"=>"",
       "filters_attributes"=>{"0"=>{"gender"=>"Select Gender", "creation_date_start"=>"", "creation_date_finish"=>"", "timezone"=>[""], "locale"=>[""], "segment"=>[""]}},
       "nb_recipients"=>"1",
       "core_bot_id"=>"1",
       "messages_attributes"=>{"0"=>{"content"=>"fdsfdfd", "buttons_attributes"=>{"0"=>{"button_text"=>"", "button_url"=>"", "_destroy"=>"false"}}, "_destroy"=>"false"}},
       "cards_attributes"=>
        {"1514217785795"=>
          {"title"=>"sdffsdfsd",
           "subtitle"=>"fsdfdsdsf",
           "button_share"=>"false",
           "buttons_attributes"=>{"0"=>{"button_text"=>"test", "button_url"=>"http://www.sddssd.fr", "_destroy"=>"false"}},
           "remote_image_url"=>"",
           "_destroy"=>"false"}}},
     "time"=>"now",
     "commit"=>"Save Draft"}
    

    What I would need is params[:letter]['cards_attributes']['1514217785795']['buttons_attributes'] but I can’t know “1514217785795”.

    Any idea how to verify is there are buttons_attributes in my params?

    #246771

    Cloudy Point
    Keymaster

    Accepted AnswerAnswer

    The key is to use Hash#values to retrieve values for the hash with an unknown key.

    input["letter"]["cards_attributes"].
      values.   # ? HERE
      map { |hash| hash["buttons_attributes"] }.
      compact   # to eliminate those having no such entry
    

    Source: https://stackoverflow.com/questions/47970197/rails-ruby-how-to-retrieve-hash-key-with-unknown-id
    Author: mudasobwa
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.