2010-08-13 62 views
2

我收到以下錯誤信息,並且想用來使用.nil?方法我可以通過識別異常來避免發生錯誤。但我不知道。如何避免紅寶石在軌道上無班級?

第40行顯示我收到錯誤...它似乎認爲contact.latest_event爲零。但不應該.nil?幫助我避免發生錯誤?謝謝...!

ActionView::TemplateError (undefined method `<=>' for nil:NilClass) on line #40 
of app/views/companies/show.html.erb: 
37:  <p> 
38:    <%= full_name(contact) %>, <%= contact.status %><%= contact.titl 
e %>, 
39:    <span class='date_added'>added <%= contact.date_entered %> 
40:      <% if !contact.latest_event.nil?%> 
41:      last event: <%= contact.latest_event.date_sent %> 
42:      <% end %> 
43:    </span> 

這裏是latest_event:

def latest_event 
    [contact_emails, contact_calls, contact_letters].map do |assoc| 
      assoc.first(:order => 'date_sent DESC') 
     end.compact.sort_by { |e| e.date_sent }.last 
end 

我想這是沒有任何模型contact_emails的可能,例如,已經完成......但我該怎麼辦,如果沒有任何那存在?

+0

請問您可以發佈'latest_event'方法的代碼嗎? – 2010-08-13 16:35:38

+0

只是做了...謝謝 – Angela 2010-08-14 03:55:21

回答

0

我相信你能解決你的問題,改變latest_event方法。

def latest_event 
    events = [contact_emails, contact_calls, contact_letters].map do |assoc| 
      assoc.first(:order => 'date_sent DESC') 
     end.compact 

    events.sort_by{ |e| e.date_sent }.last unless events.blank? 
end 

而只是一個評論:當你需要if就像這個

if !contact.latest_event.nil? 

,最好使用unless

unless contact.latest_event.nil? 
+0

現在很酷的嘗試...我實際上有除非聲明,但它是錯誤的,所以認爲我使用它錯了。所以會按照你的說法放回去,謝謝,現在就來看看吧! – Angela 2010-08-15 17:30:53

+0

哦廢話 - 仍然得到相同的錯誤....爲什麼它在做<=>即使我不使用它? – Angela 2010-08-16 21:53:15

+0

是不是'date_sent'零? – 2010-08-17 11:23:45

2

我不知道latest_event做什麼,但它看起來像你的零實際上在latest_event,因爲它正在做一個比較(<=>)。 latest_event是什麼樣子的?

+0

嗨,juts增加了它....嗯...我如何檢查它是否無錯誤出? – Angela 2010-08-14 03:55:50

0

方法< =>用於實現基本運算符<,>,=>,...(請參閱module Comparable)。但是我看不到你在哪裏使用它們,實際上......它可能在latest_event方法中。

旁白,下面的語句是等價的:

if !contact.latest_event.nil? 
unless contact.latest_event.nil? 
if contact.latest_event # Only nil and false evaluate as false 
+1

我發現這3箇中的最後一個是最好的:) – theIV 2010-08-13 21:35:23

0

你隱式使用<=>當您使用sort_by

這裏有一個可能的解決方法,假設date_sent持有Date對象:

def latest_event 
    [contact_emails, contact_calls, contact_letters].map do |assoc| 
    assoc.first(:order => 'date_sent DESC') 
    end.compact.sort_by { |e| e.date_sent.nil? ? Date.new : e.date_sent }.last 
end 

你的問題是,你的一些記錄具有在date_sentnull。當您請求ruby按此值排序時,ruby不知道如何將nilDate進行比較。要進行排序比較,ruby使用<=>(有關此運算符的內容,請參閱文檔herehere)。

在上面的代碼中,我添加了替代佔位符Date的邏輯,當date_sentnil時。那個佔位符是4月1日-4712(一個非常古老的日期)。這意味着date_sent == nil的記錄將首先放在排序結果中。

如果您date_sentTime,那麼你可以使用Time.at(0)而不是Date.new