Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include Active Storage attachments in Active Record query

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?

like image 994
martini-bonanza Avatar asked Dec 03 '22 10:12

martini-bonanza


1 Answers

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
like image 146
arieljuod Avatar answered Jan 11 '23 23:01

arieljuod