【问题标题】:How to avoid attachment N+1如何避免依附N+1
【发布时间】:2018-11-30 21:36:40
【问题描述】:

给定

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

在尝试显示每个头像时,如何避免对active_storage_attachmentsactive_storage_blobs 进行 N+1 次查询?

【问题讨论】:

    标签: ruby-on-rails rails-activestorage select-n-plus-1


    【解决方案1】:

    根据ActiveStorage's examples,您可以使用#with_attached_A,其中A是附件的名称:

    User.all.with_attached_avatar
    

    同样,如果你有很多附件,你可以使用#with_attached_As

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      相关资源
      最近更新 更多