Skip to content

Commit 0bb56ec

Browse files
committed
Add querying section to ActiveStorage guides
1 parent 04690da commit 0bb56ec

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

guides/source/active_storage_overview.md

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -662,6 +662,35 @@ are stored before the form is submitted, they can be used to retain uploads when
662662
<%= form.file_field :avatar, direct_upload: true %>
663663
```
664664

665+
## Querying
666+
667+
Active Storage attachments are just ordinary Active Record associations behind the scenes, so you can use the usual `joins` / `where` toolbox to look up records whose attachments meet specific criteria.
668+
669+
### `has_one_attached`
670+
671+
`has_one_attached` creates a `has_one` association called `"<name>_attachment"` and a `has_one :through` association called `"<name>_blob"`.
672+
Need every user whose avatar is a PNG?
673+
674+
```ruby
675+
User
676+
.joins(:avatar_blob)
677+
.where(active_storage_blobs: { content_type: "image/png" })
678+
```
679+
680+
### `has_many_attached`
681+
682+
`has_many_attached` creates a `has_many` association called `"<name>_attachments"` and a `has_many :through` association called `"<name>_blobs"` (note the plural).
683+
Want all messages whose images are videos instead of photos?
684+
685+
```ruby
686+
Message
687+
.joins(:images_blobs)
688+
.where(active_storage_blobs: { content_type: "video/mp4" })
689+
```
690+
691+
Because these are plain SQL joins, remember that the query filters on the **`ActiveStorage::Blob`**, not the attachment record. You can combine the blob predicates above with any other scope conditions, just as you would with any other Active Record query.
692+
693+
665694
Removing Files
666695
--------------
667696

0 commit comments

Comments
 (0)