Search code examples
ruby-on-rails-5eager-loadingrails-activestorage

Rails: How to eager load attachments belonging to an associated model?


In my Rails v5.2.4.1 app (ruby v2.6.1), I am loading a bunch of messages using a working query. Each message belongs_to a :user model, and user has_one_attached :photo. I am eager loading users with all the messages like this:

Message.<query>.includes(:user)

Right now, this code photo.attached? ? photo : 'default_avatar.png' results in queries like this:

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", 32], ["record_type", "User"], ["name", "photo"], ["LIMIT", 1]]

How do I eager load user.photo and user.photo.attached? with my query?


Solution

  • After some research, I found the answer to this. I had overlooked it in the docs. The problem is solved by using <association>_attachment in the includes. So in my question, the eager loading (for photo) is done using the following code

    Message.<query>.includes(user: :photo_attachment)