有以下型号:
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
如果end_time或start_time为Nil,我有关于Nil的错误。我怎么样?如果以前的验证是正确的,如何执行time_comparison验证?
答案 0 :(得分:3)
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
答案 1 :(得分:1)
我想,你必须检查开始和结束时间是否为零:
def time_comparison
errors[:base] << 'Incorrect end time' if start_time && end_time && start_time > end_time
end