Skip to content

Commit 66a8dbb

Browse files
committed
Add Count The Number Of Records By Attribute as a Rails til
1 parent 0ec8b98 commit 66a8dbb

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1078 TILs and counting..._
13+
_1079 TILs and counting..._
1414

1515
---
1616

@@ -653,6 +653,7 @@ _1078 TILs and counting..._
653653
- [Comparing DateTimes Down To Second Precision](rails/comparing-datetimes-down-to-second-precision.md)
654654
- [Conditional Class Selectors in Haml](rails/conditional-class-selectors-in-haml.md)
655655
- [Convert A Symbol To A Constant](rails/convert-a-symbol-to-a-constant.md)
656+
- [Count The Number Of Records By Attribute](rails/count-the-number-of-records-by-attribute.md)
656657
- [Create A Custom Named References Column](rails/create-a-custom-named-references-column.md)
657658
- [Creating Records of Has_One Associations](rails/creating-records-of-has-one-associations.md)
658659
- [Custom Validation Message](rails/custom-validation-message.md)
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Count The Number Of Records By Attribute
2+
3+
In [Count How Many Records There Are Of Each
4+
Type](postgres/count-how-many-records-there-are-of-each-type.md), I walked
5+
through how to use SQL (in PostgreSQL) to get a count of how many records there
6+
are with each unique value in a given column. This is something I tend to do
7+
with a `type` or `status` column.
8+
9+
We can ask the same question with Rails, with very little code. It produces a
10+
nearly identical query and the same results.
11+
12+
```ruby
13+
> Book.group(:status).count
14+
#=> { nil => 123, "published" => 611, "draft" => 364, "review" => 239 }
15+
```
16+
17+
We've picked the `Book` model and we want it to group books by their `status`.
18+
Tacking on the `#count` at the end tells it to apply the `count` aggregate. The
19+
result is a hash of each unique value of the specified attribute (`status`)
20+
paired with the count.

0 commit comments

Comments
 (0)