在Active Record查询中包括Active Storage附件

mar*_*nza 3 activerecord ruby-on-rails rails-activestorage

使用Rails 5.2和Active Storage,我设置了Item一些类images

class Item < ApplicationRecord
  has_many_attached :images
end
Run Code Online (Sandbox Code Playgroud)

我想用来ActiveRecord::QueryMethods.includes向,加载images标准的Rails东西has_many,但是:

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?")
Run Code Online (Sandbox Code Playgroud)

任何想法如何使其工作?

mar*_*nza 9

\xe2\x80\xa6aa 我找到了答案:

\n\n
Item.reflections.keys\n=> ["location", "images_attachments", "images_blobs", "taggings", "base_tags", "tag_taggings", "tags"]\n
Run Code Online (Sandbox Code Playgroud)\n\n

Active Storage 生成的关联的名称是,images_attachments尽管它可以通过 访问Item#images。这是解决方案:

\n\n
Item.includes(:images_attachments)\n  Item Load (0.6ms)  SELECT  "items".* FROM "items" LIMIT $1  [["LIMIT", 11]]\n  ActiveStorage::Attachment Load (0.6ms)  SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_type" = $1 AND "active_storage_attachments"."name" = $2 AND "active_storage_attachments"."record_id" IN ($3, $4, $5, $6, $7)  [["record_type", "Item"], ["name", "images"], ["record_id", 3], ["record_id", 2], ["record_id", 4], ["record_id", 5], ["record_id", 1]]\n=> #<ActiveRecord::Relation [\xe2\x80\xa6]>\n
Run Code Online (Sandbox Code Playgroud)\n


ari*_*uod 7

ActiveStorage提供了一种防止N + 1查询的方法

Gallery.where(user: Current.user).with_attached_photos
Run Code Online (Sandbox Code Playgroud)

https://api.rubyonrails.org/classes/ActiveStorage/Attached/Macros.html#method-i-has_many_attached

因此,在您的情况下:

Item.with_attached_images
Run Code Online (Sandbox Code Playgroud)