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:
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.
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.
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".
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With