2014-01-09 48 views
2

Thereis以下模型:未定義的方法`>」:NilClass在定製驗證

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是零。我該如何適應?只有在以前的驗證正確的情況下如何執行time_comparison驗證?

+0

START_TIME有'nil',但無論如何,你可以使用'validates_presence:START_TIME,END_TIME:,:值'而不是你指定的? –

+0

我不理解你,對不起 – malcoauri

+1

用'validates_presence:start_time,:end_time,:value'替換'validates:start_time,:end_time,:value,presence:true'。然後重建數據庫結構,避免遷移過程中出現的所有錯 –

回答

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

我認爲,你必須檢查的開始和結束時間不爲零:

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