在rails中填充带有哈希数组的选择框

时间:2014-01-20 08:21:02

标签: ruby-on-rails ruby-on-rails-3

无论如何我已经创建了一个哈希数组:

@example= ['A' => '1', 'B' => '2']

或数组

@example=[1,2]

这里你有钥匙(英文名称)和价值( 通用等价物。)

我想要做的是让一个下拉单选框使用这些 正确渲染它的键/值属性,

  <%= f.collection_select @example %>

...这不起作用,但我想要的是生成表单代码......

#from HASH
<select >
<option value="1">A</option>
<option value="2">B</option>
</select>

#from array
<select>
<option>1</option>
<option>2</option>
</select>

任何帮助都非常感激。

1 个答案:

答案 0 :(得分:5)

有关:

@example = [["A", 1, {:class=>"bold"}], ["B", 2], ["C", 3]] # {:class=> "bold"} is optional, use only if you need html class for option tag.

尝试:

<%= form_for @whatever do |f|%>
# some code here..
<%= f.select :example, options_for_select(@example) %>
# rest of the code..
<% end %>

或者您可以使用:

<%= form_for @whatever do |f|%>
# some code here..
<%= f.select :example, @example %> # I am guessing that maybe you can not pass hash here for option tag.
# rest of the code..
<% end %>

没有form_for:

<%= select_tag :example, @example %>
# or
<%= select_tag :example, options_for_select(@example)%>