當我嘗試和驗證兩個日期時間在他們的模型屬性,我得到如下:驗證一個日期時間要晚於其他
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
你確定'startDate'或'endDate'不能是'nil'嗎? – tessi
validates_presence_of:car_id,:service_id,:startDate,:endDate –
該方法中顯示的代碼沒有任何問題。錯誤在其他地方,結果是'startDate'或'endDate'之一爲零。可能是'endDate',並且有些東西試圖從'nil'強制它進行比較。對於這個粗略的調試驗證嘗試在方法的頂部添加'p startDate,endDate'。 –