Reputation: 1224
I am seeking to populate a select list in a form with options for user gender. I have a learning Rails book that uses a similar approach for credit card options by creating an array in the model and then referencing it in the view. Unfortunayely when I use this approach I receive an error referencing the line in my view stating: "uninitialized constant GENDER_OPTIONS"
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable, :confirmable,
:recoverable, :rememberable, :trackable, :validatable
GENDER_OPTIONS = { "Male" => :true, "Female" => :false, "Unspecified" => :nil}
has_many :discussions
has_many :comments
end
<div>
<%= f.label :gender %><br />
<%= f.select :gender, User::GENDER_OPTIONS %>
</div>
Upvotes: 0
Views: 1323
Reputation: 8220
Try using helper and locale.
# app/helpers/application_helper.rb
def gender_lists
I18n.t(:gender_lists).map { |key, value| [ value, key ] }
end
# config/locale/en.yml
en:
gender_lists:
"": Unspecified
"true": Male
"false": Female
and on your view, you can do this
<div>
<%= f.label :gender %><br />
<%= f.select :gender, gender_lists %>
</div>
===
Note :
Just suggestion, user string
type data instead of boolean
Upvotes: 1
Reputation: 3963
"sex" should not be stored as a boolean - it is not a true/false value. Aside from labelling half of the people in your database as "false", when you write SQL queries you (and and future developers) will have to know what the magic values are.
And boolean fields should not have three potential states (true/false/nil) - that's just asking for trouble.
To make your database understandable from the schema side, set the field to be a string, and store the values "male", "female", or "unspecified" (or just blank).
Then ask yourself: why on earth do you actually need to ask people about their sex? Unless it's a dating website, or medical DB; otherwise it's just personal info for personal info's sake - you might as well be asking them their shoe size (or any other bodily part).
Upvotes: 2