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 erro开发者_运维问答rs 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.
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) }
Try COUNTRY_CODES.keys
if you only want to check with the keys in the hash.
Hows this?
validates :country, :presence => true,
:inclusion => { :in => COUNTRY_CODES.keys.map{|c| c.to_s}
精彩评论