在带有rails的select中将选项值设置为数组索引

时间:2010-10-24 08:56:25

标签: ruby-on-rails html-select

我想使用rails collection_selectoptions_for_select创建一个select标记,其中包含一个非基于模型的数组项。选项的值应该是每个项的数组索引。

示例:['first', 'second', 'third']的所需输出:

<select id="obj_test" name="obj[test]">
    <option value="0">first</option> 
    <option value="1">second</option> 
    <option value="2">third</option> 
</select> 

4 个答案:

答案 0 :(得分:13)

如果the_array = ['first', 'second', 'third']

,您也可以将其作为一行
<%= select "obj", "test", the_array.each_with_index.map {|name, index| [name,index]} %>

我早在Rails 2.3.14测试过这个。

答案 1 :(得分:11)

我在问题中提到项目不是数据库中的对象,它们只是字符串,如下所示:

the_array = ['first', 'second', 'third']

感谢Lichtamberg,我这样做了:

f.select(:test, options_for_select(Array[*the_array.collect {|v,i| [v,the_array.index(v)] }], :selected => f.object.test)) %>

给出了所需的输出:

<option value="0">first</option>
<option value="1">second</option>
<option value="2">third</option>

我没有使用Hash,因为订单很重要,我的ruby版本不大于1.9

答案 2 :(得分:5)

Ruby&gt; = 1.9.3

Ruby已经(出色地)在with_indexmap上添加了collect方法,因此您现在可以执行以下操作:

options_for_select ['first', 'second', 'third'].collect.with_index.to_a

这将为您提供以下HTML:

<option value="0">first</option>
<option value="1">second</option>
<option value="2">third</option>

赞美Matz等人

答案 3 :(得分:3)

@people = [{:name => "Andy", :id => 1}, {:name => "Rachel", :id => 2}, {:name => "test", :id => 3}]
# or
peop = ["Rachel", "Thomas",..]
@people = Hash[*peop.collect { |v| [v, a.index(v)] }.flatten]

然后

select_tag "people", options_from_collection_for_select(@people, "name", "id")
# <select id="people" name="people"><option value="1">Andy</option>....</select>

另一种解决方案(HAML格式):

=select_tag("myselect")
  =options_for_select(array)

请参阅http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select