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

Gre*_*een 1 ruby-on-rails ruby-on-rails-3

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

@example= ['A' => '1', 'B' => '2']
Run Code Online (Sandbox Code Playgroud)

或数组

@example=[1,2]
Run Code Online (Sandbox Code Playgroud)

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

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

  <%= f.collection_select @example %>
Run Code Online (Sandbox Code Playgroud)

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

#from HASH
<select >
<option value="1">A</option>
<option value="2">B</option>
</select>
Run Code Online (Sandbox Code Playgroud)

要么

#from array
<select>
<option>1</option>
<option>2</option>
</select>
Run Code Online (Sandbox Code Playgroud)

任何帮助真的很感激.

Sur*_*rya 5

对于:

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

尝试:

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

或者您可以使用:

<%= 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 %>
Run Code Online (Sandbox Code Playgroud)

没有form_for:

<%= select_tag :example, @example %>
# or
<%= select_tag :example, options_for_select(@example)%>
Run Code Online (Sandbox Code Playgroud)