Skip to content

Commit 40a3f2f

Browse files
authored
Merge pull request rails#55310 from thiagodiniz/main
Add querying section to ActiveStorage guides
2 parents 46d2afa + dd4a422 commit 40a3f2f

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

guides/source/active_storage_overview.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -662,6 +662,31 @@ 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 Active Record associations behind the scenes, so you can use the usual [query methods](active_record_querying.html) to look up records for attachments that meet specific criteria.
668+
669+
### `has_one_attached`
670+
671+
[`has_one_attached`](https://api.rubyonrails.org/classes/ActiveStorage/Attached/Model.html#method-i-has_one_attached) creates a `has_one` association named `"<name>_attachment"` and a `has_one :through` association named `"<name>_blob"`.
672+
To select every user where the avatar is a PNG, run the following:
673+
674+
```ruby
675+
User.joins(:avatar_blob).where(active_storage_blobs: { content_type: "image/png" })
676+
```
677+
678+
### `has_many_attached`
679+
680+
[`has_many_attached`](https://api.rubyonrails.org/classes/ActiveStorage/Attached/Model.html#method-i-has_many_attached) creates a `has_many` association called `"<name>_attachments"` and a `has_many :through` association called `"<name>_blobs"` (note the plural).
681+
To select all messages where images are videos rather than photos you can do the following:
682+
683+
```ruby
684+
Message.joins(:images_blobs).where(active_storage_blobs: { content_type: "video/mp4" })
685+
```
686+
687+
The query will filter on the [**`ActiveStorage::Blob`**](https://api.rubyonrails.org/classes/ActiveStorage/Blob.html), not the [attachment record](https://api.rubyonrails.org/classes/ActiveStorage/Attachment.html) because these are plain SQL joins. You can combine the blob predicates above with any other scope conditions, just as you would with any other Active Record query.
688+
689+
665690
Removing Files
666691
--------------
667692

0 commit comments

Comments
 (0)