Skip to content

Commit ddf1c51

Browse files
committed
Add Filter ActiveStorage Blobs To Only Images as a Rails TIL
1 parent 60020d6 commit ddf1c51

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-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://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1611 TILs and counting..._
13+
_1612 TILs and counting..._
1414

1515
See some of the other learning resources I work on:
1616
- [Ruby Operator Lookup](https://www.visualmode.dev/ruby-operators)
@@ -1022,6 +1022,7 @@ If you've learned something here, support my efforts writing daily TILs by
10221022
- [Ensure A Rake Task Cannot Write Data](rails/ensure-a-rake-task-cannot-write-data.md)
10231023
- [Ensure Migrations Use The Latest Schema](rails/ensure-migrations-use-the-latest-schema.md)
10241024
- [Ensure Record Saved With after_commit Callback](rails/ensure-record-saved-with-after-commit-callback.md)
1025+
- [Filter ActiveStorage Blobs To Only Images](rails/filter-active-storage-blobs-to-only-images.md)
10251026
- [Find Or Create A Record With FactoryBot](rails/find-or-create-a-record-with-factory-bot.md)
10261027
- [Find Records With Multiple Associated Records](rails/find-records-with-multiple-associated-records.md)
10271028
- [Force All Users To Sign Out](rails/force-all-users-to-sign-out.md)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Filter ActiveStorage Blobs To Only Images
2+
3+
If your Rails app is using `ActiveStorage` for both images and ActionMailbox
4+
emails, then you're going to have a mix of both in the `active_storage_blobs`
5+
table.
6+
7+
```sql
8+
> select id, filename, content_type from active_storage_blobs limit 2;
9+
10+
| id | filename | content_type |
11+
|----|--------------------|----------------|
12+
| 1 | shirt-brothers.jpg | image/jpeg |
13+
| 2 | message.eml | message/rfc822 |
14+
```
15+
16+
In that case, you are going to want to make sure that any part of your system
17+
that only cares to deal with images filters down to only blobs where the
18+
`content_type` is one that you care about.
19+
20+
I expect that there might be a couple different image `content_type` values
21+
that my system handles, so I filter my `active_storage_blobs` like so:
22+
23+
24+
```ruby
25+
@images =
26+
ActiveStorage::Blob
27+
.where(content_type: %w[image/jpeg image/png image/gif image/webp])
28+
.order(created_at: :desc)
29+
.first(10)
30+
```

0 commit comments

Comments
 (0)