2

I am trying to build a relatively simple named scope in my Products class. Oddly, if I issue the query directly (a la Product.where()), I get the results I expect. However, if this query is changed to a scope declaration, the result set is nil.

Why does my query work when called directly but produce nothing when it is made into a scope? Here's the actual code:

scope :is_queued, where("status = 2 OR (status = 0 AND status_expires > ?)", DateTime.now )# <-- returns nil
Product.where("status = 2 OR (status = 0 AND status_expires > ?)", DateTime.now) # <-- returns 1+ results (as expected)

Thank you!

Tom

Tom Corelis
  • 4,990
  • 11
  • 35
  • 48

1 Answers1

3

Scopes defined with scope are evaluated once, when the scope is defined - so DateTime.now refers to when your app instance first started.

Try:

scope :is_queued, lambda { where("status = 2 OR (status = 0 AND status_expires > ?)", DateTime.now) }
Chowlett
  • 45,935
  • 20
  • 116
  • 150
  • Turned out to be a combination of this, plus a forgotten-about empty `is_queued` class method hanging out further down the file. Oops! :-) Thank you. – Tom Corelis Mar 03 '12 at 15:18