From 82c1f872e0aa5233833b26fb72043aa570831e4a Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 21 Jul 2020 16:33:29 -0500 Subject: [PATCH] Add Get An Empty ActiveRecord Relation as a rails til --- README.md | 3 +- rails/get-an-empty-activerecord-relation.md | 33 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 rails/get-an-empty-activerecord-relation.md diff --git a/README.md b/README.md index 74ab58e..55195b5 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_938 TILs and counting..._ +_939 TILs and counting..._ --- @@ -580,6 +580,7 @@ _938 TILs and counting..._ - [Force All Users To Sign Out](rails/force-all-users-to-sign-out.md) - [Generating And Executing SQL](rails/generating-and-executing-sql.md) - [Get An Array Of Values From The Database](rails/get-an-array-of-values-from-the-database.md) +- [Get An Empty ActiveRecord Relation](rails/get-an-empty-activerecord-relation.md) - [Get The Column Names For A Model](rails/get-the-column-names-for-a-model.md) - [Hash Slicing](rails/hash-slicing.md) - [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md) diff --git a/rails/get-an-empty-activerecord-relation.md b/rails/get-an-empty-activerecord-relation.md new file mode 100644 index 0000000..91b91fd --- /dev/null +++ b/rails/get-an-empty-activerecord-relation.md @@ -0,0 +1,33 @@ +# 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. + +```ruby +> result +[] +> result.class +Book::ActiveRecord_Relation +``` + +It's an empty [`ActiveRecord` +relation](https://api.rubyonrails.org/classes/ActiveRecord/Relation.html). + +You can get an instance of an empty `ActiveRecord` relation without +constructing a _no result_ query. + +```ruby +> 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](https://stackoverflow.com/questions/4877931/how-to-return-an-empty-activerecord-relation)