views:

1161

answers:

2

I have a select box that looks like this (within a form_for)

  <%=f.select(:whatever_id, {"blah"=>0, "blah2"=>1, "blah3"=>2, "blah4"=>3}, {:include_blank => true}) %>

and the output is good, but weird... like this:

<select id="personal_information_whatever_id" name="personal_information[whatever_id]"><option value=""></option>
<option value="1">blah2</option>

<option value="2">blah3</option>
<option value="0">blah</option>
<option value="3">blah4</option></select>

But I want it to go in order... what is happening, and how can I correct it?

Edit: I feel like the answer has to do with this

You can never be guaranteed of any order with hashes. You could try .sort() to sort the values in alphabetical order.

is there anything I can use aside from a hash?

A: 

The problem is that the options parameter is a hash, and hashes have no guaranteed order.

This should work for you

  <%= f.select(:whatever_id, ([["blah",0],["blah2",1],["blah3",2]]), {:include_blank => true}) %>

Edit in response to your comment: For collections see collection_select

DanSingerman
cool, thanks HermanD. I was just typing that :) Any easy workarounds in terms of collections?
Yar
+7  A: 

Yes, you should use an array of arrays. The easiest way with your example would be something like this:

<%=f.select(:whatever_id, [["blah", 0], ["blah2", 1], ["blah3", 2], ["blah4", 3]], {:include_blank => true}) %>

This should suffice. Take a look at the docs at api.rubyonrails.com too.

Ola Bini
Excellent. Just what I needed. THANKS.
Yar
But the hash syntax looks so sexy! haha - thanks.
Jon Smock
@Jon I don't know if you're kidding and I know you'll never see this since it doesn't show up in your responses, but: I hate that stupid hash syntax. I just find it so awkward to type. But it works, so...
Yar
Is there an easy way to reference the options later if you have an array of arrays? With my hash I could do a case statement later (or something similar) and say if(value == OPTIONS[:blah2])...etc
Brian Armstrong