Rails / ruby :如何检索具有未知id的哈希密钥

问题描述 投票:-1回答:1

我想检查我的参数中是否有button_attributes。但是,数组有一个随机ID,所以我无法验证button_attributes是否存在。

这是参数:

{"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"}

我需要的是params[:letter]['cards_attributes']['1514217785795']['buttons_attributes'],但我不知道“1514217785795”。

任何想法如何验证我的参数中是否有buttons_attributes?

ruby-on-rails ruby
1个回答
1
投票

关键是使用Hash#values检索具有未知密钥的哈希值。

input["letter"]["cards_attributes"].
  values.   # ⇐ HERE
  map { |hash| hash["buttons_attributes"] }.
  compact   # to eliminate those having no such entry
© www.soinside.com 2019 - 2024. All rights reserved.