nulltek
nulltek

Reputation: 3337

Calculating Elapsed time in Rails

I'm writing an app where I need to compare two :datetime fields and get the difference to display as an "elapsed" time from the start of the record. I think I have my code right, but I keep getting the below error. Can someone tell me what I'm doing wrong?

Error on view:
undefined method `-' for nil:NilClass line 26:
26:     <td><%= link_to call.elapsed_time, call %></td>

Call.rb (abbreviated)
before_create :set_dispatched_time

def set_dispatched_time
  self.dispatched_time = Time.now
end

def elapsed_time
  self.dispatched_time - Time.now
end

My fields in PG are set as :datetime so that I can compute times (I did have them as strings.. ooops) but for some reason it's not calculating. Do I need to call Time.parse first or something like that? I'm not really sure which direction to go. I just want to subtract the dispatched_time field from Time.now

Upvotes: 1

Views: 2528

Answers (1)

Matzi
Matzi

Reputation: 13925

Your self.dispatched_time does not exist according the error message, it is nil. This can be because before_create is call when first time the opject is persisted into the database, and this particular instance is not yet saved.

First try to make sure, that this variable has a value, or assign a default value in case if it is not assigned. E.g.:

def elapsed_time
  Time.now - (self.dispatched_time || Time.now)
end

Upvotes: 3

Related Questions