Where would this logic go in Rails?

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?

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

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs