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

1 Answer 1

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) }
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.