Reputation: 23713
In the database, I store 0 if gender is female and 1 if gender is male.
I have a form field like this:
<%= myobject.select(:gender, options_for_select([['Male', 1], ['Female', 0]]), {:prompt => 'Select Gender'})%>
Which works well when:
However, if the field is Female it shows the Select Gender option. I believe is because the 0 in the database is thought as false when is retrieved (because Rails assumes 0 in Mysql is false) and therefore in the select it thinks it has to prompt the non value text.
How should I deal with this situation assuming I can't touch the database structure.
Upvotes: 3
Views: 1894
Reputation: 4877
moved this to an answer instead of a comment as it is actually an optional way of doing it if you can't change the schema.
If you can change it: string, :length => 1 # (M/F)
otherwise you can use a converter like this:
myobject.rb
def m_f
myobject.gender ? 'M' : 'F'
end
attr_accessor :gender_string
before_save :convert_gender
def convert_gender
self.gender = myobject.gender_string == 'M' ? 1 : 0
end
_form.html.erb
<%= myobject.select(:gender_string, options_for_select([['Male', 'M'], ['Female', 'F']]), {:prompt => 'Select Gender', :selected => myobject.m_f})%>
you'll then need to convert the data back again once the form is submitted.
Upvotes: 2