Dun Peal Dun Peal - 3 months ago 11
SQL Question

SELECTing all ActiveRecord instances where date difference is smaller than X hours

I have a Rails 4

ActiveRecord
model with two
DateTime
fields:
dt1
and
dt2
.

How do I retrieve all instances of this model for which
dt2
is less than X (say, 18) hours after
dt1
?

Answer

Try this:

Model.where(%q{ dt2 - dt1 < interval '18 hours' })

18 hours can be a variable you assign dynamically through a param.

dt_diff = '22 days' # or 18 hours or 3 years
Model.where(%q{ dt2 - dt1 < interval dt_diff })
Comments