Using Rails 5.2 and Active Storage, I set up an Item
class with some images
:
class Item < ApplicationRecord
has_many_attached :images
end
I'd like to use ActiveRecord::QueryMethods.includes
to eager-load the images
, pretty standard Rails stuff with has_many
, but:
Item.includes(:images)
=> ActiveRecord::AssociationNotFoundError ("Association named 'images' was not found on Item; perhaps you misspelled it?")
Item.includes(:attachments)
=> ActiveRecord::AssociationNotFoundError ("Association named 'attachments' was not found on Item; perhaps you misspelled it?")
Item.includes(:active_storage_attachments)
=> ActiveRecord::AssociationNotFoundError ("Association named 'active_storage_attachments' was not found on Item; perhaps you misspelled it?")
Any idea how to make it work?
ActiveStorage provides a method to prevent N+1 queries
Gallery.where(user: Current.user).with_attached_photos
https://api.rubyonrails.org/classes/ActiveStorage/Attached/Model.html#method-i-has_many_attached
So, in your case:
Item.with_attached_images
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