Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you solve N+1 for ActiveStorage URLs?

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)
like image 265
Strawberry Avatar asked Aug 10 '18 11:08

Strawberry


People also ask

How ActiveStorage works?

Using Active Storage, an application can transform image uploads or generate image representations of non-image uploads like PDFs and videos, and extract metadata from arbitrary files.

What is Activerecord in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.


1 Answers

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.

like image 86
George Claghorn Avatar answered Sep 22 '22 23:09

George Claghorn