如何从rails 3中的哈希创建下拉列表 [英] how to create dropdown from a hash in rails 3
问题描述
在rails 3中,如何从哈希创建下拉列表
我的User类中有以下代码
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 %>
但它抱怨
undefined method `merge' for :value:Symbol
那么什么是正确的创建下拉菜单的方法
So what is the proper way to create the dropdown?
谢谢
推荐答案
:
<%= f.collection_select :gender, User.genders, :first, :last %>
修改:说明:
collection_select
将致电 each
在你给的对象( User.genders
这里)和两个方法(第一
和 last
here)。它大致相当于这样的东西:
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
当您调用在一个Hash 上的doc.org/core/classes/Hash.html#M000742> ,它会产生一个
Array
。这些值可以使用第一个
和最后一个
方法进行检索。
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.
这篇关于如何从rails 3中的哈希创建下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!