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)
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With