3

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

2
  • Why nil as first argument to collection_select? Commented Jul 12, 2011 at 6:16
  • i dont know.. i read from the api doc...and some blog article do thing like that..i just copy Commented Jul 12, 2011 at 6:34

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Michael, it is working ..... but why to_arry will help??? can you explain a little bit..coz i am new to ruby...
Actually it doesn't because Hash has an each method. I removed it and added a some explanations.
It worked for me, but I had to make sure that the symbol of the first argument (:gender in the example), had an entry under my models :attr_accessor. Thank you for your answer...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.