我需要根据哈希值中的值创建一个选择框。
例如,我有一个'东西'而''东西'有各种各样的状态字段:
1 => 'State A'
2 => 'State B'
可通过物品上的方法获得。
如何从中构建选择标记?
答案 0 :(得分:52)
正如施罗克威尔所说:
Hash.each |a|
返回a = [key, value]
形式的数组,因此对于散列@status_fields
,您可以写:
<%= collection_select('thing', 'status', @status_fields, :first, :last) %>
或者,如果您希望键出现在选择列表中,并且值指向选择列表值,则:
<%= collection_select('thing', 'status', @status_fields, :last, :first) %>
这将选择thing.status给出的选项,如果返回nil,则不选择任何内容
如果您想创建任何与对象无关的选择,请使用
<%= select_tag('name', options_from_collection_for_select(@status_fields, :first, :last, '2')) %>
其中'2'是所需选择的索引
PS:我没有足够的声誉来修改原帖或评论
答案 1 :(得分:8)
select "foo", "bar", @hash_object
或
select "foo", "bar", @hash_object.map { |h| [h.key, h.value] }
我可能会首先反转你的哈希,使关键指向值
答案 2 :(得分:7)
select helper method将接受{ text_displayed_in_select => select_value }
形式的哈希值,因此您可能希望{哈希invert。
答案 3 :(得分:4)
Hash.each |a|
返回a = [key, value]
形式的数组,因此对于散列@status_fields
,您可以写:
<%= collection_select('thing', 'status', @status_fields, :first, :last) %>
或者,如果您希望键出现在选择列表中,并且值指向选择列表值,则:
<%= collection_select('thing', 'status', @status_fields, :last, :first) %>