I want to do the following: Find all articles with where Time.now is between article.due_date and article.due_date - 8.hours. I'm having a lot of trouble trying to get it right. Any help would be much appreciated.

Thanks!

share|improve this question

80% accept rate
What is it that you are having problems with? – Jimmy Stenke Mar 7 '11 at 18:23
feedback

1 Answer

up vote 0 down vote accepted

Who said that algebra was worthless?

The two conditions you stated in your question.

T <= DUE
T >= DUE - 8h

Are the same as these two conditions.

DUE >= T
DUE <= T + 8h    

You can apply now apply this to a query and/or scope without having to do datetime gymnastics in your database.

named_scope :near_due, lambda {{ :conditions => ["due_date >= ? AND due_date <= ?", Time.now, Time.now + 8.hours] }}
share|improve this answer
Ha. I just solved this myself. Had to relookup the rules for inequalities. Probably don't need the lambda unless we're passing the hours, which may indeed be a good idea. Have an accepted answer for your work though :) – Dave G Mar 7 '11 at 19:20
You definitely need the lambda, otherwise Time.now will only be evaluated the first time your model is cached. – jdl Mar 7 '11 at 19:25
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.