How to return an empty ActiveRecord relation?

dzajic picture dzajic · Feb 2, 2011 · Viewed 74k times · Source

If I have a scope with a lambda and it takes an argument, depending on the value of the argument, I might know that there will not be any matches, but I still want to return a relation, not an empty array:

scope :for_users, lambda { |users| users.any? ? where("user_id IN (?)", users.map(&:id).join(',')) : [] }

What I really want is a "none" method, the opposite of "all", that returns a relation that can still be chained, but results in the query being short-circuited.

Answer

steveh7 picture steveh7 · Apr 3, 2012

There is a now a "correct" mechanism in Rails 4:

>> Model.none 
=> #<ActiveRecord::Relation []>