N+1 query issue is coming at the time of fetching variant.
Model:
`class YoyakuShouhin < ApplicationRecord
has_many_attached :shouhin_images do |attachable|
attachable.variant :desktop, resize: ‘500×500’, gravity: ‘center’, format: :webp
attachable.variant :mobile, resize: ‘400×400’, gravity: ‘center’, format: :webp
attachable.variant :desktop_l, resize: ‘700×700’, gravity: ‘center’, format: :webp
end
end`
Query:
shouhins = YoyakuShouhin.includes(shouhin_images_attachments: :blob).order(:shouhin_number)
Feting all images:
object.shouhin_images.where(deleted: false).order('priority').map { |image| cdn_for(image.variant(:desktop).processed.key) }
N+1 query issue:
[active_model_serializers] ActiveStorage::VariantRecord Load (25.7ms) SELECT "active_storage_variant_records".* FROM "active_storage_variant_records" WHERE "active_storage_variant_records"."blob_id" = $1 AND "active_storage_variant_records"."variation_digest" = $2 LIMIT $3 [["blob_id", 17658], ["variation_digest", "dfN0cpZZzpYcgFl9hL0o122mIBI="], ["LIMIT", 1]] TRANSACTION (61.2ms) COMMIT [active_model_serializers] ↳ app/serializers/api/v2/xmas/yoyaku_shouhin_serializer.rb:124:in
block in shouhin_mobile_images’
↳ app/middleware/request_response_history.rb:27:in block in request_response_history' [active_model_serializers] ActiveStorage::Attachment Load (73.3ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = $1 AND "active_storage_attachments"."record_type" = $2 AND "active_storage_attachments"."name" = $3 LIMIT $4 [["record_id", 12079], ["record_type", "ActiveStorage::VariantRecord"], ["name", "image"], ["LIMIT", 1]] [active_model_serializers] ↳ app/serializers/api/v2/xmas/yoyaku_shouhin_serializer.rb:124:in
block in shouhin_mobile_images’
[active_model_serializers] ActiveStorage::Blob Load (68.2ms) SELECT “active_storage_blobs”.* FROM “active_storage_blobs” WHERE “active_storage_blobs”.”id” = $1 LIMIT $2 [[“id”, 17659], [“LIMIT”, 1]]`
I want to solve n+1 query issue