mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 23:28:02 +00:00
Add Count The Number Of Records By Attribute as a Rails til
This commit is contained in:
@@ -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)
|
||||
|
||||
20
rails/count-the-number-of-records-by-attribute.md
Normal file
20
rails/count-the-number-of-records-by-attribute.md
Normal file
@@ -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.
|
||||
Reference in New Issue
Block a user