Rails 6: Scope for Models without ActiveStorage Attachments

Dana Scheider (he/they)
1 min readFeb 4, 2021

This was a problem that plagued me for over an hour, and none of the answers I found on Google helped. I have a Rails 6 application with a model that has one ActiveStorage attachment. I needed a scope for all models that do not have a file attached. This is the model class:

ActiveRecord conveniently includes a scope called with_attached_file , which returns, intuitively enough, an ActiveRecord relation with all the models that have a file attached. Unfortunately, there is no corresponding without_attached_file scope.

Although there were several answers on StackOverflow that purported to solve this problem, none of them worked for me (possibly because I’m using Rails 6 and they use Rails 5, although I’m not actually sure of the reason). The solution that ended up working for me was this:

Note that you will need to change :file_attachment to whatever you’ve called your attachment. So if your model has_one_attached :image, for example, it would be left_joins(:image_attachment).

And that’s it! I hope this is able to save someone else the pain I had to deal with!

--

--

Dana Scheider (he/they)

Senior Engineer at CashApp, formerly at Envato & New Relic