malcoauri
malcoauri

Reputation: 12209

undefined method `>' for nil:NilClass in custom validation

Thereis the following model:

class TimeCorrection < ActiveRecord::Base
    validates :start_time, :end_time, :value, presence: true

    validate :time_comparison

    def time_comparison
        errors[:base] << 'Incorrect end time' if start_time > end_time
    end
end

I've got error about Nil if end_time or start_time are Nil. How can I fit? How to execute time_comparison validation only if the previous validation is correctly?

Upvotes: 2

Views: 740

Answers (2)

Jacek
Jacek

Reputation: 412

I think, You have to check if start and end time are not nil:

def time_comparison
    errors[:base] << 'Incorrect end time' if start_time && end_time && start_time > end_time
end

Upvotes: 1

Ivan Denysov
Ivan Denysov

Reputation: 1502

class TimeCorrection < ActiveRecord::Base
    validates :start_time, :end_time, :value, presence: true

    validate :time_comparison

    def time_comparison
        errors[:base] << 'Incorrect end time' if start_time && end_time && start_time > end_time
    end
end

Upvotes: 3

Related Questions