select_tag来自Rails上的哈希红宝石

时间:2018-07-23 17:03:01

标签: html ruby-on-rails ruby ruby-on-rails-5

我有一个哈希

{"1":"value1","2":"value 2","4":"test"}

我想要一个像这样的select_tag

<select>
<option id="1">value1</option>
<option id="2">value 2</option>
<option id="4">test/option>
</select>

我尝试了

select_tag "col", options_from_collection_for_select(col.map { |k,v| [k,v] },:required => true,:include_blank => false)

1 个答案:

答案 0 :(得分:0)

只需使用 options_for_select

<%= select_tag "col", options_for_select(hash.map { |k,v| [v,k] }, { required: true, include_blank: false}) %>

请注意,[v,k]取反以给出正确的值和显示名称