Alexis
Alexis

Reputation: 149

Rails ActiveStorage - has_on_attached/has_many_attached associations is load by default

I got a problem with ActiveStorage, Currently I have has_on_attachedand has_many_attached relation on my Model

Every time I call my model it loads the relation as below:

ActiveStorage::Attachment Load (4.2ms) 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", 4934], ["record_type", "User"], ["name", "profile_picture"], ["LIMIT", 1]]

ActiveStorage::Attachment Exists (0.9ms) SELECT 1 AS one 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", 4934], ["record_type", "User"], ["name", "home_pictures"], ["LIMIT", 1]]

How can I disable this behaviour by default ?

Upvotes: 2

Views: 975

Answers (1)

Jay Dorsey
Jay Dorsey

Reputation: 3662

You can use Model.with_attached_images.find(:id) to avoid the N+1

https://github.com/rails/rails/tree/master/activestorage#examples

I'm not sure if you can disable eager loading the attachments, but the above should help clean up a little bit.

Upvotes: 4

Related Questions