1

I am trying to use validates_timeliness to ensure that SliderImage.start is always before SliderImage.stop:

class SliderImage < ActiveRecord::Base

  validates_datetime :start, :stop
  validates :start, :timeliness => {:before => stop}

end

But of course stop is not defined yet. How can I accomplish this?

Jay
  • 2,861
  • 3
  • 29
  • 51

2 Answers2

5

A simpler way to use this validation without installing any gem is calling a method to validate:

class Course < ActiveRecord::Base
  validate :start_date_before_end_date

  def start_date_before_end_date
    if self.start_date > self.end_date
      errors.add(:start_date, "Start date should be before end date")
    end
  end
end
AdamCooper86
  • 3,957
  • 1
  • 13
  • 19
Anderson Lopes
  • 639
  • 7
  • 10
  • As an aside, if you are going to use this validator in multiple places, consider making it a global validator. Followed this article with great success. http://www.rails-dev.com/custom-validators-in-ruby-on-rails-4 – AdamCooper86 Dec 19 '15 at 19:41
4

The stop value must be called on the record object being evaluated. The shorthand version is pass the symbol :stop, and this be assumed to be method on the record which will called at validation time.

Otherwise you can use a lambda like so

lambda {|r| r.stop } 

I would tend to write your validation as

validates_datetime :start
validates_datetime :stop, :after => :start

p.s. I'm the plugin author :)

Adzap
  • 56
  • 2