Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate model field: if value equals a key in a hash

In an initializer I have a huge COUNTRY_CODES hash, with format:

{ :us => "United States, :de => "Germany" }

In my model I want to validate that the entered value is:

  • present
  • a key of my country code hash

How do I apporach this?

I can't use:

validates :country, :presence => true,
                    :inclusion => { :in => COUNTRY_CODES }

I've tried custom validators, but I get method errors when the value is nil, e.g. when I try to use value.to_sym, causing me to validate the validator and it becomes messy.

Trying to figure out the most DRY and efficient way of doing this.

like image 375
Fred Fickleberry III Avatar asked Sep 20 '11 10:09

Fred Fickleberry III


People also ask

How do you get the key of a hash in Ruby?

Ruby | Hash key() functionHash#key() is a Hash class method which gives the key value corresponding to the value. If value doesn't exist then return nil.

How do I validate in Ruby on Rails?

This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".


1 Answers

You need to collect COUNTRY_CODES keys(symbols) as strings and validate for the inclusion. So use:

validates :country, :presence => true,:inclusion => { :in => COUNTRY_CODES.keys.map(&:to_s) }
like image 169
Soundar Rathinasamy Avatar answered Sep 22 '22 15:09

Soundar Rathinasamy