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

前端 未结 2 2057
-上瘾入骨i
-上瘾入骨i 2020-12-30 20:53

I\'ve got a project where there is a CURRENCY and COUNTRY table. There\'s a PRICE model that requires a valid currency and country code, so I have the following validation:

相关标签:
2条回答
  • 2020-12-30 21:27

    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
    
    0 讨论(0)
  • 2020-12-30 21:50

    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_exists
    
    def currency_code_exists
        errors.add(:base, "Currency code must exist") unless Currency.all_codes.include?(self.currency_code)
    end
    
    0 讨论(0)
提交回复
热议问题