Search code examples
ruby-on-railsrails-activestorage

Ruby on Rails: How can I create a scope that checks whether there is an attachment?


I have a movie object with a "poster" attachment through active storage (has_one_attached :poster)

I would like to create a scope to retrieve all movies that do not have a poster attached, however this here does not work:

scope :no_poster, -> { where (poster: nil) }

It results in an error saying

Unknown column 'movies.poster' in 'where clause'

(which sort of makes sense to me :)

How do I create such a scope?


Solution

  • Just answering my own question here if ever somebody searches for this: engineersmnky's comment is spot on, the relationship name IS poster_attachment, so in order to create a scope that searches for movies without a poster is

    scope :no_poster, -> { where.missing(:poster_attachment) }