Dun Peal
Dun Peal

Reputation: 17679

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?

Upvotes: 1

Views: 133

Answers (1)

Mathias
Mathias

Reputation: 459

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}'" })

Upvotes: 3

Related Questions