1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00
Files
til/rails/get-an-empty-activerecord-relation.md

856 B

Get An Empty ActiveRecord Relation

When you query for something (with #where) and there are no results matching that query, you get something that looks like an empty array ([]), but it's not quite.

> result
[]
> result.class
Book::ActiveRecord_Relation

It's an empty ActiveRecord relation.

You can get an instance of an empty ActiveRecord relation without constructing a no result query.

> Book.none
[]
> Book.none.class
Book::ActiveRecord_Relation

I can think of a couple scenarios where this would be useful:

  • as a default value for a method parameter
  • as a test value for a method that expects to have an ActiveRecord relation passed in

source