views:

115

answers:

3

I get the following error, and thought by using the .nil? method I could avoid getting an error by identifying the exception. But I don't.

Line 40 shows I am getting an error...it seems to think that contact.latest_event is nil. But shouldn't .nil? help me avoid getting the error? Thanks...!

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>

Here is 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

I guess it's possible none of the Models contact_emails, for example, have been done...but what do I do if there aren't any that exist?

+2  A: 

I don't know what latest_event does, but it seems like your nil is actually in latest_event since it's doing a comparison (<=>). What does latest_event look like?

theIV
Hi, juts added it....hmmm...how do I check if it is nil without erroring out?
Angela
A: 

The method <=> is used to implement basic operators as <, >, =>, ... (see the module Comparable). But I can't see where you use them, actually ... it may be inside the latest_event method.

Asides, the following statements are equivalent:

if !contact.latest_event.nil?
unless contact.latest_event.nil?
if contact.latest_event   # Only nil and false evaluate as false
giraff
I find the last of those 3 to be the nicest :)
theIV
A: 

I believe you can solve your problem changing the latest_event method.

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

And just a comment: when you need ifs like this

if !contact.latest_event.nil?

it's better to use unless:

unless contact.latest_event.nil?
j.
cool trying it out now...I actually had unless statement, but it was erroring out so thought I was using it wrong. So will put it back as you said, thanks, checking it out now!
Angela
oh crap -- still getting the same error....why is it doing the <=> even though I don't use it?
Angela
Isn't `date_sent` nil?
j.