runchu
runchu

Reputation: 151

How to set the order of validation methods ruby on rails?

I am a Ror beginner. There is a model Lecture, I want to validate the format of start time and end time firstly, and then check if the end time is after start time. It works well when the format is valid but once the format is wrong it comes with: undefined method `<' for nil:NilClass. How to makes start_must_be_before_end_time triggered only when the format is valid? Thanks!

Here is the code:

class Lecture < ActiveRecord::Base
belongs_to :day
belongs_to :speaker
validates :title, :position, presence: true



validates :start_time, format: { with: /([01][0-9]|2[0-3]):([0-5][0-9])/,
         message: "Incorrect time format" }


validates :end_time, format: { with: /([01][0-9]|2[0-3]):([0-5][0-9])/,
        message: "Incorrect time format" }


validate :start_must_be_before_end_time

private
def start_must_be_before_end_time
    errors.add(:end_time, "is before Start time") unless start_time < end_time
end

end

Upvotes: 1

Views: 1524

Answers (2)

cruncher
cruncher

Reputation: 54

You can go another way:

errors.add(:end_time, "is before Start time") unless start_time.nil? || end_time.nil? || start_time < end_time

Upvotes: -1

Uzbekjon
Uzbekjon

Reputation: 11823

There are no guarantees on the order of validations that are defined by validates methods. But, the order is guaranteed for custom validators that are defined with validate method.

From docs:

You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered.

Alternatively

You can only run your validation method if all other validations pass:

validate :start_must_be_before_end_time, :unless => Proc.new { |obj| obj.times_valid? }

# Then, define `times_valid?` method and check that start_time and end_time are valid

Upvotes: 3

Related Questions