Rails 3 validates inclusion of when using a find (how to proc or lambda) Rails 3 validates inclusion of when using a find (how to proc or lambda) ruby ruby

Rails 3 validates inclusion of when using a find (how to proc or lambda)


Just use a proc, like so:

validates :currency_code,          :presence => true,          :inclusion => { :in => proc { Currency.all_codes } }validates :country_code,          :presence => true,          :inclusion => { :in => proc { Country.all_codes } }

It's worth noting for anyone else who may stumble across this that the proc also has the record accessible as a parameter. So you can do something like this:

validates :currency_code,          :presence => true,          :inclusion => { :in => proc { |record| record.all_codes } }def all_codes  ['some', 'dynamic', 'result', 'based', 'upon', 'the', 'record']end


Note: This answer is true for old versions of Rails, but for Rails 3.1 and above, procs are accepted.

It must not accept Procs. You can use a custom validation method to do the same thing:

validate :currency_code_existsdef currency_code_exists    errors.add(:base, "Currency code must exist") unless Currency.all_codes.include?(self.currency_code)end