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

Time:11-03

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?

CodePudding user response:

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) }

CodePudding user response:

Rails 6.1 adds a query method missing to search for orphan records within ActiveRecord.

Try

scope :no_poster, -> { where.missing(:poster) }
  • Related