Search code examples
ruby-on-railsrails-activestorageselect-n-plus-1

How to avoid attachment N+1


Given

class User < ApplicationRecord
  has_one_attached :avatar

  def avatar_path
    Rails.application.routes.url_helpers.rails_blob_path avatar,
                                                         disposition: 'inline',
                                                         only_path: true
  end
end

class UsersController < ApplicationController
  def index
    @users = User.all
  end
end

How can I avoid N+1 queries to active_storage_attachments and active_storage_blobs when trying to display each avatar?


Solution

  • As per ActiveStorage's examples, you can use #with_attached_A, where A is the name of the attachment:

    User.all.with_attached_avatar
    

    Similarly, if you had many attached, you can use #with_attached_As.