Rails greater_than model validation against model attribute

前端 未结 4 1482
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-12 15:35

I\'ve got a Trip model, which among other attributes has a start_odometer and end_odometer value. In my model, i\'d like to validate that the end odometer is larger than the st

相关标签:
4条回答
  • 2021-02-12 15:43

    It's a bit kludgy, but this seems to work:

    validates_numericality_of :end_odometer, :greater_than => :start_odometer.to_i, :allow_blank => true
    
    0 讨论(0)
  • 2021-02-12 15:53

    You'll probably need to write a custom validation method in your model for this...

    validate :odometer_value_order
    
    def odometer_value_order
      if self.end_odometer && (self.start_odometer > self.end_odometer)
        self.errors.add_to_base("End odometer value must be greater than start odometer value.")
      end
    end
    
    0 讨论(0)
  • 2021-02-12 16:01

    You can validate against a model attribute if you use a Proc.

    In rails4 you would do something like this:

    class Trip < ActiveRecord::Base
      validates_numericality_of :start_odometer, less_than: ->(trip) { trip.end_odometer }
      validates_numericality_of :end_odometer, greater_than: ->(trip) { trip.start_odometer }
    end
    
    0 讨论(0)
  • 2021-02-12 16:03

    You don't necessarily need a custom validation method for this case. In fact, it's a bit overkill when you can do it with one line. jn80842's suggestion is close, but you must wrap it in a Proc or Lambda for it to work.

    validates_numericality_of :end_odometer, :greater_than => Proc.new { |r| r.start_odometer }, :allow_blank => true
    
    0 讨论(0)
提交回复
热议问题