how to create dropdown from a hash in rails 3

2019-05-10 16:28发布

问题:

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.collection_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

回答1:

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.