格式复杂哈希 - simple_form gem

时间:2013-05-15 21:42:31

标签: ruby ruby-on-rails-3 hash simple-form

我有这样的嵌套哈希:

  LANGUAGE_DETAILS =  {
                       BG: {
                              Name: 'Български',
                              Flag: ''
                           },
                       EN: {
                              Name: 'English',
                              Flag: ''
                           },
                       RU: {
                              Name: 'Руский',
                              Flag: ''
                           },
                       UK: {
                              Name: 'Украински',
                              Flag: ''
                           }
                    }

并且需要像下面的哈希一样格式化它:

 {
      BG: 'Български',
      EN: 'English',
      RU: 'Руский',
      UK: 'Украински'
  }

为了将它用作simple_form输入参数,如下所示:

<%= f.input :language_code, collection: SecurityUser::LANGUAGE_DETAILS,
            label_method: :last,
            value_method: :first,
            as: :radio_buttons , label: 'Choose language' %>

有没有办法在此上下文中将SecurityUser :: LANGUAGE_DETAILS哈希转换为新哈希,或者我应该在模型中创建哈希?

1 个答案:

答案 0 :(得分:2)

你可以这样做:

Hash[LANGUAGE_DETAILS.map{|k, h| [k, h[:Name]]}]