1
0
mirror of https://github.com/jbranchaud/til synced 2026-01-03 07:08:01 +00:00

Add Filter ActiveStorage Blobs To Only Images as a Rails TIL

This commit is contained in:
jbranchaud
2025-03-08 16:18:44 -06:00
parent 60020d6e0e
commit ddf1c51fd9
2 changed files with 32 additions and 1 deletions

View File

@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
_1611 TILs and counting..._
_1612 TILs and counting..._
See some of the other learning resources I work on:
- [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
- [Ensure A Rake Task Cannot Write Data](rails/ensure-a-rake-task-cannot-write-data.md)
- [Ensure Migrations Use The Latest Schema](rails/ensure-migrations-use-the-latest-schema.md)
- [Ensure Record Saved With after_commit Callback](rails/ensure-record-saved-with-after-commit-callback.md)
- [Filter ActiveStorage Blobs To Only Images](rails/filter-active-storage-blobs-to-only-images.md)
- [Find Or Create A Record With FactoryBot](rails/find-or-create-a-record-with-factory-bot.md)
- [Find Records With Multiple Associated Records](rails/find-records-with-multiple-associated-records.md)
- [Force All Users To Sign Out](rails/force-all-users-to-sign-out.md)

View File

@@ -0,0 +1,30 @@
# Filter ActiveStorage Blobs To Only Images
If your Rails app is using `ActiveStorage` for both images and ActionMailbox
emails, then you're going to have a mix of both in the `active_storage_blobs`
table.
```sql
> select id, filename, content_type from active_storage_blobs limit 2;
| id | filename | content_type |
|----|--------------------|----------------|
| 1 | shirt-brothers.jpg | image/jpeg |
| 2 | message.eml | message/rfc822 |
```
In that case, you are going to want to make sure that any part of your system
that only cares to deal with images filters down to only blobs where the
`content_type` is one that you care about.
I expect that there might be a couple different image `content_type` values
that my system handles, so I filter my `active_storage_blobs` like so:
```ruby
@images =
ActiveStorage::Blob
.where(content_type: %w[image/jpeg image/png image/gif image/webp])
.order(created_at: :desc)
.first(10)
```