rails erb form helper options_for_select :selected

46,672

Solution 1

In your code, your options_for_select() call sets the selected value to "gender" and does not attempt to use the value from your form object.

Please see the docs for options_for_select() for usage examples.

options_for_select(['Mare', 'Stallion', 'Gelding'], f.object.gender)
options_for_select(['Mare', 'Stallion', 'Gelding'], :selected => f.object.gender)

Alternatively, you can do this, which will already use the gender() value for your form object:

<%= f.select :gender, ['Mare', 'Stallion', 'Gelding'] %>

Solution 2

By the way, if you are using :include_blank => true, this will set your current selection to blank even though the form "knows" what is selected.

Share:
46,672
Drew Harris
Author by

Drew Harris

I've been developing software since Jr. High School. I've been developing software professionally for nearly 20 years. I'm always trying to keep up with the latest technology. Things are always changing and so it's important to not allow my skills to get stale. Right now I favor Ruby on Rails, HTML5, CSS3, Linux, Apache and MySQL. I'm fairly new to RoR. I'm interested in learning Objective C for native iOS Development.

Updated on July 30, 2022

Comments

  • Drew Harris
    Drew Harris almost 2 years

    I have an edit form in erb.

    <%= form_for @animal do |f| %>
    

    Within the code I have a select with options:

    <%= f.select :gender, options_for_select([['Mare'], ['Stallion'], ['Gelding']], :selected => :gender) %>
    

    However, the select is not showing the correct selected value. What could I be doing wrong? I can get it to work if I hardcode it but of course that is not a viable option.

    • Scott
      Scott about 10 years
      +1 for asking a comment relating to horses, which is exactly what I'm working on as well. :)
  • Gagan Gami
    Gagan Gami almost 8 years
    even though added :include_blank => true by this :selected => f.object.gender it will work