Question

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

Was it helpful?

Solution

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) }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top