Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Konnor Rogers
Konnor Rogers

Posted on

     

Querying ActiveStorage Attachments

The problem

You want to find all the ActiveRecord models that either do / do not have a record attached to them.

The solution

Let's say you have aPost class which has one image attached like so:

classPost<ApplicationRecordhas_one_attached:imageend
Enter fullscreen modeExit fullscreen mode

To query for allPosts that do not have an image attached the syntax would look like this:

Post.left_joins(:image_attachment).where(active_storage_attachments:{id:nil})
Enter fullscreen modeExit fullscreen mode

This will return all posts that do not have an image. If you want to find all posts thathave an image attached, you would use a#not clause in there like so:

Post.left_joins(:image_attachment).where.not(active_storage_attachments:{id:nil})
Enter fullscreen modeExit fullscreen mode

has_many_attached

This can even be extended tohas_many_attached by using the plural form of:image_attachment like so:

classPost<ApplicationRecordhas_many_attached:imagesend# Query for all without attachmentsPost.left_joins(:image_attachments).where(active_storage_attachments:{id:nil})# Query for all with attachmentsPost.left_joins(:image_attachments).where.not(active_storage_attachments:{id:nil})
Enter fullscreen modeExit fullscreen mode

Final Syntax

The syntax for attachments is fairly straightforward like so:

ModelName.left_joins(:<attachment_name>_attachment[s]).where(active_storage_attachments:{<column>:<value>})
Enter fullscreen modeExit fullscreen mode

And thats it! Good luck and enjoy your new found query power!

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
sidran83 profile image
Pierre Deveix
  • Joined

Thanks for your post, it was very useful for me!
I just have something to add:
In my case, when the Post Model has many attached images, the query will be
Post.left_joins(:images_attachments).where(active_storage_attachments: { id: nil })
(the attachment_name must be in plural)

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Full stack ruby on rails web developer
  • Location
    Providence, RI
  • Work
    Software Developer
  • Joined

More fromKonnor Rogers

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp