I want to create a select tag using rails collection_select
or options_for_select
with the items of an array which are not model based. The value of the option should be the array index of each item.
Example: desired output for ['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>
You can also do this as one line if the_array = ['first', 'second', 'third']
<%= select "obj", "test", the_array.each_with_index.map {|name, index| [name,index]} %>
I have tested this as far back as Rails 2.3.14.
I mentioned in the question that the items are not objects in the database, they're just strings, like this:
the_array = ['first', 'second', 'third']
Thanks to Lichtamberg, I've done it like this:
f.select(:test, options_for_select(Array[*the_array.collect {|v,i| [v,the_array.index(v)] }], :selected => f.object.test)) %>
Which gives the desired output:
<option value="0">first</option>
<option value="1">second</option>
<option value="2">third</option>
I did not use Hash
, because the order is important, and my ruby version is not greater than 1.9
Ruby has (brilliantly) added a with_index
method on map
and collect
so you can just do the following now:
options_for_select( ['first', 'second', 'third'].collect.with_index.to_a )
And that'll get you the following HTML:
<option value="0">first</option>
<option value="1">second</option>
<option value="2">third</option>
Praise Matz et al.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With