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\""
What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.
Active Storage uses two tables in your application's database named active_storage_blobs and active_storage_attachments . After creating a new application (or upgrading your application to Rails 5.2), run rails active_storage:install to generate a migration that creates these tables.
1 What is Active Storage? Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects.
By default in the development environment, Active Storage stores all uploaded images on your local disk in the storage subdirectory of the Rails application directory. That's the file you uploaded!
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) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With