Validating that end_date doesn't come before start_date

A user enters two dates. On before_save, I'm trying to validate that the second date does _not_ come before the first.

Assume that start_date and end_date are Datetime objects. If I call the following method from the model on before_save, why is no error added to end_date?

def assure_dates_in_order   start = Time.at(self.start_date)   last = Time.at(self.end_date)   if (start - last) > 0       errors.add(:base, "can't come before start date")   end end

I know know that this code is quite ugly. I could not get the Datetime objects to compare any other way.

Anyone who can make this code beautiful and functional is awesome.

If both are dates, this will work:

def assure_dates_in_order     errors.add_to_base("can't come before start date") unless self.start_date < self.end_date end

knb wrote:

btw, after looking at the way your error message reads, it looks like you want this to appear on the “end_date” field. This would do that:

    def assure_dates_in_order
errors.add(:end_date,"can't come before start date") unless self.start_date < self.end_date
end

William Pratt wrote:

http://svn.viney.net.nz/things/rails/plugins/validates_date_time/