Validate model field: if value is equal to hash key

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

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

In my model, I want to confirm that the entered value:

  • is present
  • key of my country code hash

How to do it?

I can not use:

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

I tried custom validators, but I get method errors when the value is nil. when I try to use value.to_sym, forcing me to check the validator and it becomes messy.

Trying to figure out the harshest and most effective way to do this.

+7
source share
3 answers

You need to collect the keys (characters) COUNTRY_CODES as strings and confirm the inclusion. Therefore use:

 validates :country, :presence => true,:inclusion => { :in => COUNTRY_CODES.keys.map(&:to_s) } 
+14
source

Try COUNTRY_CODES.keys if you only want to verify the keys in the hash.

+4
source

Does that mean?

 validates :country, :presence => true, :inclusion => { :in => COUNTRY_CODES.keys.map{|c| c.to_s} 
+1
source

All Articles