rails erb form helper options_for_select :selected
Asked Answered
C

2

30

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.

Cristicristian answered 1/10, 2013 at 15:53 Comment(1)
+1 for asking a comment relating to horses, which is exactly what I'm working on as well. :)Maramarabel
P
71

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'] %>
Pandanus answered 1/10, 2013 at 16:2 Comment(0)
C
5

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.

Clydesdale answered 11/2, 2014 at 18:38 Comment(1)
even though added :include_blank => true by this :selected => f.object.gender it will workRollerskate

© 2022 - 2024 — McMap. All rights reserved.