views:

27

answers:

1

Hi,

Is there any way I can make my rails model validations execute in a particular order and skip certain validations if previous validations are not satisfied.

For eg: I have 2 input fields start_date and end_date. I have two validate methods in my model

One of them checks the dates are less than "12/31/#{Date.today.year + 1}"

 def end_date_in_range
    if self.end_date
      errors.add_to_base("Enter a date before #{Date.today.year + 1}") if self.end_date > Date.parse("12/31/#{Date.today.year + 1}")
    end
 end

I have another validation which steps through the dates from start date to end date

  def
    (self.start_date.to_date .. self.end_date.to_date).inject(0) { |sum, n|  ... }
  end

Now if the user enters an end_date like 12/31/20101, this fails the first validation but looks like it either continues to check the next validation or the second validation is executed first and in both cases hangs my application while processing this request. I would like it to check the first validation and return the error to the user and not step through the dates in the second validation.

thanks, ash

A: 

use elsif

 def end_date_in_range
    if self.end_date
      errors.add_to_base("Enter a date before #{Date.today.year + 1}") if self.end_date > Date.parse("12/31/#{Date.today.year + 1}")
    elsif  #second validation test

    end
 end
Salil