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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)