17

How do you preload all the records with their URLs?

This is what I am doing in my jbuilder to get the URLs:

# views/users/index.json.jbuilder
...
json.avatar_url user.avatar.attached? && rails_blob_url(user.avatar)
...


Comment
    has_one :user

User
    has_one_attached :avatar

How would you preload all the users and their avatars?


Comments.includes(users: :avatar)

yields the following error:

ActiveRecord::AssociationNotFoundError (Association named 'avatar' was not found on User; perhaps you misspelled it?)

The same error pops up when executing:

User.includes(:avatar)
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
Strawberry
  • 66,024
  • 56
  • 149
  • 197

1 Answers1

32

For a singular attachment named :avatar, Active Storage adds a with_attached_avatar scope that preloads the relevant associations:

@users.with_attached_avatar.each do |user|
  # ...
end

See the API documentation for has_one_attached.

Felix
  • 4,510
  • 2
  • 31
  • 46
George Claghorn
  • 26,261
  • 3
  • 48
  • 48