Archive for November, 2010

Why is my select value not selected?

November 19, 2010

Hours battling this one. Symptom: select tag in a form was not displaying the value of the attribute from the database, although one could select a new value and have it saved as expected.

Had a simple (!) select tag, looked something like this:

  <%= :state, options_for_us_state %>

No matter what manner of manipulation I did, including explicitly setting :selected =>, would cause the value of the state attribute from the ActiveRecord object to be selected upon page presentation.

After digging through the Rails code, I noticed that the select form helper was calling options_for_select. Looking at that code, I noticed that if the container of options that is passed in is a String, no :selected or :disabled processing is done.

But I’m not passing in a string, I’m…oops, my options_for_us_state helper was already calling options_for_select, thus giving me a string, thus bypassing the :selected and :disabled processing.

Interestingly, it created the select tag just fine, which is what did me in for so long.

Seems like possibly a Rails oversight. The doc for options_for_select doesn’t say that you can pass in a String. Nor does it say that you can’t, and Strings do respond to the each method.

But still, it’s odd behavior, no?