How to return an empty ActiveRecord relation? How to return an empty ActiveRecord relation? ruby-on-rails ruby-on-rails

How to return an empty ActiveRecord relation?


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

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


A more portable solution that doesn't require an "id" column and doesn't assume there won't be a row with an id of 0:

scope :none, where("1 = 0")

I'm still looking for a more "correct" way.


Coming in Rails 4

In Rails 4, a chainable ActiveRecord::NullRelation will be returned from calls like Post.none.

Neither it, nor chained methods, will generate queries to the database.

According to the comments:

The returned ActiveRecord::NullRelation inherits from Relation and implements the Null Object pattern. It is an object with defined null behavior and always returns an empty array of records without quering the database.

See the source code.