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
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})
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})
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})
Final Syntax
The syntax for attachments is fairly straightforward like so:
ModelName.left_joins(:<attachment_name>_attachment[s]).where(active_storage_attachments:{<column>:<value>})
And thats it! Good luck and enjoy your new found query power!
Top comments(1)
For further actions, you may consider blocking this person and/orreporting abuse