From 66a8dbb2dc0b72a748e70be1fea476af71c28cfe Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 9 Mar 2021 19:36:14 -0600 Subject: [PATCH] Add Count The Number Of Records By Attribute as a Rails til --- README.md | 3 ++- ...ount-the-number-of-records-by-attribute.md | 20 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 rails/count-the-number-of-records-by-attribute.md diff --git a/README.md b/README.md index 25b482d..eee1bc6 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_1078 TILs and counting..._ +_1079 TILs and counting..._ --- @@ -653,6 +653,7 @@ _1078 TILs and counting..._ - [Comparing DateTimes Down To Second Precision](rails/comparing-datetimes-down-to-second-precision.md) - [Conditional Class Selectors in Haml](rails/conditional-class-selectors-in-haml.md) - [Convert A Symbol To A Constant](rails/convert-a-symbol-to-a-constant.md) +- [Count The Number Of Records By Attribute](rails/count-the-number-of-records-by-attribute.md) - [Create A Custom Named References Column](rails/create-a-custom-named-references-column.md) - [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md) - [Custom Validation Message](rails/custom-validation-message.md) diff --git a/rails/count-the-number-of-records-by-attribute.md b/rails/count-the-number-of-records-by-attribute.md new file mode 100644 index 0000000..1642fb2 --- /dev/null +++ b/rails/count-the-number-of-records-by-attribute.md @@ -0,0 +1,20 @@ +# Count The Number Of Records By Attribute + +In [Count How Many Records There Are Of Each +Type](postgres/count-how-many-records-there-are-of-each-type.md), I walked +through how to use SQL (in PostgreSQL) to get a count of how many records there +are with each unique value in a given column. This is something I tend to do +with a `type` or `status` column. + +We can ask the same question with Rails, with very little code. It produces a +nearly identical query and the same results. + +```ruby +> Book.group(:status).count +#=> { nil => 123, "published" => 611, "draft" => 364, "review" => 239 } +``` + +We've picked the `Book` model and we want it to group books by their `status`. +Tacking on the `#count` at the end tells it to apply the `count` aggregate. The +result is a hash of each unique value of the specified attribute (`status`) +paired with the count.