title: Rails Instance Method with if/else on empty field
body: <p>I wrote an instance method in my model for calculating a time difference between two dates. Works when the second date exists, but need to add an <code>if else</code> condition to return a string if the second date does not exist. I have </p>
  
  <pre><code>class Incident  
  def calculate_elapsed(difference)
  if self.closed.nil?
    @difference = "Open"
  else
    d1 = self.created
    d2 = self.closed
    difference = d2 - d1
    @difference = difference.to_i
  end 
  </code></pre>
  
  <p>When I try to load an Incident which I know to have an empty <code>closed</code> date I get </p>
  
  <p><code>You have a nil object when you didn't expect it!</code></p>
  
  <p><code>You might have expected an instance of Array.</code></p>
  
  <p><code>The error occurred while evaluating nil.-</code></p>
  
  <p>Puzzled by the error because I figured <code>if self.closed.nil?</code>
  was checking for the nil object. What can I do to get this to work? </p>
  
  <p>I'm not certain this is the right way to handle what I'm trying to do, so open to any and all suggestions (i.e. this should be a class method, helper, etc. Had it in my controller previously and figured this was a step in the right direction).</p>
  
  <p>What's further confusing is that I can call this method in a partial and it returns the "Open" string wherever the closed date does not exist.</p>
  
  <p><strong>Edit</strong></p>
  
  <p>Here's what I got working-</p>
  
  <p>Model:</p>
  
  <pre><code>class Incident  
  def calculate_elapsed
  if self.closed.blank?
    @difference = "Complaint Open"
  else
    d1 = created
    d2 = closed
    difference = d2 - d1
    difference_clean = difference.to_i
    @difference = difference_clean.to_s + ' Days'
  end 
  end
  </code></pre>
  
  <p>show.html.erb</p>
  
  <pre><code>&lt;%= @incident.calculate_elapsed %&gt;
  </code></pre>
  
  <p>_incidents.html.erb partial</p>
  
  <pre><code>&lt;%= incident.calculate_elapsed %&gt;
  </code></pre>