Ryan
Ryan

Reputation: 661

Rails ActiveStorage scope for when file is attached

When using ActiveStorage, how do you create a scope for when files are attached.

For example:

class Check < ActiveRecord::Base
  has_one_attached :image
end

I want something like Check.has_attached_image to return only records where there is an existing attached image.

I know that ActiveStorage provides a with_attached_image scope. But that doesn't seem to be working:

irb(main):009:0> Check.with_attached_image.to_sql => "SELECT \"checks\".* FROM \"checks\""

Upvotes: 13

Views: 3918

Answers (2)

Tom Rossi
Tom Rossi

Reputation: 12066

This includes a scope for both when an attachment exists and when it doesn't exist:

class Check < ActiveRecord::Base
  has_one_attached :image

  scope :has_image, -> { joins(:image_attachment) }
  scope :missing_image, -> { where.missing(:image_attachment) }

end

Upvotes: 2

Zoran Majstorovic
Zoran Majstorovic

Reputation: 1609

Main purpose of the scope with_attached_image is to avoid N+1 queries (to include the attached blobs in your query).

To return only records where there is an existing attached image, you can create a scope in the Check model like this:

scope :has_attached_image, -> { joins(image_attachment: :blob) }

Update from comments:

scope :has_attached_image, -> { joins(:image_attachment) }

Upvotes: 21

Related Questions