views:

24

answers:

2

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> 
A: 
@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

Lichtamberg
The items of my array are strings, not active records, with attributes like `name` or `id`.
True Soft
Sorry, corrected my post
Lichtamberg
How could I create the collection `@people` from an array? Suppose I have `['Andy', 'Rachel', 'test']`, or anything else, because I now don't know what array I will get at runtime.
True Soft
And how do you get which name is id = 3 f.e.?
Lichtamberg
Updated my post..
Lichtamberg
I don't care about which name is for an id, I'm only interested in the index the user selects. There's an error in your last post: there should be `peop.index(v)` instead of `a.index(v)`. However, I get an error: `undefined method 'name' for ["", 0]:Array`.
True Soft
Maybe this helps you: http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select see my updated post..
Lichtamberg
A: 

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

True Soft