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 if else condition to return a string if the second date does not exist. I have
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
When I try to load an Incident which I know to have an empty closed date I get
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.-
Puzzled by the error because I figured if self.closed.nil?
was checking for the nil object. What can I do to get this to work?
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).
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.
Edit
Here’s what I got working-
Model:
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
show.html.erb
<%= @incident.calculate_elapsed %>
_incidents.html.erb partial
<%= incident.calculate_elapsed %>
The error should be somewhere else, because
nil?method is defined on Objects andnilis also an object.As my last comment probably helped, possibly your class definition in you Rails environment was outdated, so restarting the application forced Rails to reload the source.
You can also reload the classes with
reload!method for e.g. in Rails console.