Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting option value as array index in a select with rails

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> 
like image 266
True Soft Avatar asked Oct 24 '10 08:10

True Soft


3 Answers

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.

like image 53
Jason Avatar answered Nov 25 '22 04:11

Jason


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

like image 43
True Soft Avatar answered Nov 25 '22 05:11

True Soft


Ruby >= 1.9.3

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.

like image 30
Joshua Pinter Avatar answered Nov 25 '22 06:11

Joshua Pinter