Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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\""

like image 743
Ryan Avatar asked Nov 07 '18 23:11

Ryan


People also ask

What is ActiveRecord in Ruby on Rails?

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.

How does active storage work in Rails?

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.

What is Activestorage?

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.

Where are active storage images stored?

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!


1 Answers

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

like image 67
Zoran Majstorovic Avatar answered Oct 27 '22 11:10

Zoran Majstorovic