True Soft
True Soft

Reputation: 8786

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> 

Upvotes: 10

Views: 20493

Answers (4)

Joshua Pinter
Joshua Pinter

Reputation: 47471

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.

Upvotes: 7

Jason
Jason

Reputation: 3806

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.

Upvotes: 13

True Soft
True Soft

Reputation: 8786

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

Upvotes: 11

BvuRVKyUVlViVIc7
BvuRVKyUVlViVIc7

Reputation: 11811

@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]

and then

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

Another solution (HAML-Format):

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

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

Upvotes: 3

Related Questions