Michael Victor
Michael Victor

Reputation: 891

Unable to make custom validation method work

I've added the following piece of code as a custom validation method for my model:

validate :delivery_date_cannot_be_after_order_date, on: :update

def delivery_date_cannot_be_after_order_date
    puts 'running method'
    if promised_delivery_date.present? && promised_delivery_date < self.created_at 
        puts 'detected error'
        errors.add(:promised_delivery_date, "can't be in the past")
    end
end

It never seems to pass the IF statement when I run this.

Later, I removed the IF statement, it still doesn't return any errors and update runs successfully.

I also tried this :

def delivery_date_cannot_be_after_order_date
    puts 'running method'
    if self.promised_delivery_date.present? && self.promised_delivery_date < self.created_at 
        puts 'detected error'
        errors.add(:promised_delivery_date, "can't be in the past")
    end
end

But still the same issue..

Here's the code when I ran it without the IF statement, I would assume that this would return an error everytime I update, but that didn't happen

Upvotes: 0

Views: 36

Answers (1)

JuanM.
JuanM.

Reputation: 432

Try to parse the date you have in your database like this: (I got something similar and worked with code as below)

def delivery_date_cannot_be_after_order_date
  puts 'running method'
  if promised_delivery_date.to_date.present? && promised_delivery_date.to_date < created_at.to_date
    puts 'detected error'
    errors.add(:promised_delivery_date, "can't be in the past")
  end
end

The thing here is that when you compare dates with < > = and those dates are casted into strings (somehow) those comparators will work only for the days and not months or years. So try parsing to an object date before you compare two dates.

See that the usage of self keyword is only necessary when you create class methods (called by the model anywhere), but in this case (I think) you need an instance method (called by any instance).

Upvotes: 1

Related Questions