开发者

how to create dropdown from a hash in rails 3

开发者 https://www.devze.com 2023-03-19 08:16 出处:网络
In rails 3, how to create a Dropdown from hash I have following code in my User class class User ...other codes

In rails 3, how to create a Dropdown from hash

I have following code in my User class

class User
  ...   other codes
  key :gender, Integer    # i use mongo db

  class << self
    def genders()
      genders = {
        '1' => 'Male',
        '2' => 'Female',
        '3' => 'Secret'
      }
    end
  end

end

In the user form, i am trying to create a gender dropdown list

<%= f.c开发者_开发问答ollection_select nil, :gender, User.genders, :key, :value %>

but it complain

undefined method `merge' for :value:Symbol

So what is the proper way to create the dropdown?

Thanks


This should work:

<%= f.collection_select :gender, User.genders, :first, :last %>

Edit: Explanations:

collection_select will call each on the object you give (User.genders here) and the two methods (first and last here) on each object. It's roughly equivalent to something like this:

User.genders.each do |object|
  output << "<option value=#{object.first.inspect}>#{h object.last}</option>"
end

When you call each on a Hash, it yields an Array of two values (the key and the value). These values can be retreived with the first and last methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号