Take the 2-minute tour ×

Help me please. I have some table with fields online and offline => when person comes online and offline. If person is still online, offline field is equal NULL and will updates only after person will go offline.

And I need calculate duration of person seanses, but using sql. I have two scopes:

scope :since, lambda { |date| where(["online >= ?", date.to_time.midnight]) }
scope :upto, lambda { |date| where(["online <= ?", date.to_time.end_of_day]) }

which helps me to filter person records. How can I calculate duration correctly after applying needed scopes? (or some other statements). Is there in activerecord something like IF NULL, and how can I use this if it really exists?


share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

you can use the sum function again.

Model.where(...condition....).sum("IFNULL(offline, CURRENT_TIMESTAMP)-online")

And I think to a scope you can simply add the sum method I used in this example

share|improve this answer
I replace CURRENT_TIMESTAMP by '#{Time.current.utc}' and it works fine. Thank you! –  InviS Oct 26 '11 at 8:22
add comment

Your Answer


