jwm
September 15, 2006, 6:26pm
1
Right now Im using helpers to populate select menus in my views.
Ex.
Helper
def some_options
[ ‘Option1’, ‘Option2’, ‘Option3’ ]
end
View
<%= select :object, :option, some_options %>
However I would also like to do my validation on these options as well,
making sure nothing is out of bounds.
So, my question is where can I place this logic to make it available for
validations and views. Should this go in the model?
jwm
September 15, 2006, 7:35pm
2
If the options aren’t coming from a database table, I would put them
in a constant array inside the model, such as:
model.rb
COUNTRY = [
[ “Canada”, “CAN” ],
[ “United States”, “US” ],
[ “England”, “UK” ],
[ “Other”, “OT” ],
].freeze
and then just use this array as the source for your select menu. If
these select objects are related to your model, you can then validate
by using something like:
validates_presence_of :country_name
or use a custom validation if it’s more complicated.
Mike
jwm
October 24, 2006, 9:15pm
3
Mike, thanks this worked very well.
For instance
GENDER = [ ‘Male’, ‘Female’ ].freeze
validates_inclusion_of :gender, :in => GENDER,
:message => “is invalid”
def self.gender_options()
GENDER
end