2013-12-18 43 views
3

當我嘗試和驗證兩個日期時間在他們的模型屬性,我得到如下:驗證一個日期時間要晚於其他

undefined method `to_datetime' for nil:NilClass

它突出了我的功能

def validate_timings 
    if (startDate > endDate) 
     errors[:base] << "Start Time must be less than End Time" 
    end 
end 

,特別是使用'>'

我認爲這可能是我處理日期的方式,但我不確定。這是日期的傳遞:

"startDate(1i)"=>"2013", 
"startDate(2i)"=>"12", 
"startDate(3i)"=>"18", 
"startDate(4i)"=>"10", 
"startDate(5i)"=>"24", 
"endDate(1i)"=>"2013", 
"endDate(2i)"=>"12", 
"endDate(3i)"=>"18", 
"endDate(4i)"=>"11", 
"endDate(5i)"=>"24", 

P.S我知道我的命名約定是不正確的,我將在未來遷移更改。

更新:這是我的全部型號

class Appointment < ActiveRecord::Base 
    belongs_to :car 
    belongs_to :service 
    accepts_nested_attributes_for :service 
    accepts_nested_attributes_for :car 

    attr_accessor :period, :frequency, :commit_button 

    validates_presence_of :car_id, :service_id, :startDate, :endDate 
    validate :validate_timings 


    def validate_timings 
     p startDate, endDate 
     if (startDate > endDate) 
      errors[:base] << "Start Time must be less than End Time" 
     end 
    end 

    def update_appointments(appointments, appointment) 
     appointments.each do |e| 
      begin 
       st, et = e.startDate, e.endDate 
      e.attributes = appointment 

      nst = DateTime.parse("#{e.startDate.hour}:#{e.startDate.min}:#{e.startDate.sec}, #{st.day}-#{st.month}-#{st.year}") 
      net = DateTime.parse("#{e.end.hour}:#{e.end.min}:#{e.end.sec}, #{et.day}-#{et.month}-#{et.year}") 
      #puts "#{nst}   :::::::::   #{net}" 
      rescue 
      nst = net = nil 
     end 
     if nst and net 
      #   e.attributes = appointment 
      e.startDate, e.endDate = nst, net 


      e.save 
     end 
    end 

    end 
end 
+0

你確定'startDate'或'endDate'不能是'nil'嗎? – tessi

+0

validates_presence_of:car_id,:service_id,:startDate,:endDate –

+0

該方法中顯示的代碼沒有任何問題。錯誤在其他地方,結果是'startDate'或'endDate'之一爲零。可能是'endDate',並且有些東西試圖從'nil'強制它進行比較。對於這個粗略的調試驗證嘗試在方法的頂部添加'p startDate,endDate'。 –

回答

1

你的比較操作是正確的。但是,當您在日期時間對象上調用此運算符時,它會嘗試將右側對象轉換爲另一個日期時間對象。

例如:「Time.now < nil」將返回: 「NoMethodError:未定義的方法`to_datetime'爲nil:NilClass」而不是無效的日期錯誤。

所以在你的情況下,你得到的錯誤意味着你沒有正確的日期時間endDate當你嘗試比較它們。

在您的模型的對象有時間加載其endDate值之前,似乎您調用了驗證方法。

+0

謝謝,我的模型最後調用validate_timings函數,但是,我在Ajax中調用窗體,所以也許我的問題在於此。 –

+0

我看不出爲什麼Ajax會導致這樣的問題。我們能否看到更多的模型代碼? –

+0

謝謝,我已將完整模型添加到我的問題中。 –

0
  1. 使用start_date,end_date作爲屬性名稱。這是慣例
  2. 如果像如果開始& & END_DATE & & END_DATE> START_DATE .....
  3. 不使用 「和」 你可以使用。使用& &
+0

謝謝,如上所述,下一次遷移時將遵守命名約定。我不相信任何這些建議會解決我的問題? –