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

时间:2019-03-24 22:13:39

标签: ruby-on-rails activerecord rails-activestorage

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

class Item < ApplicationRecord
  has_many_attached :images
end

我想使用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?")

有什么主意吗?

2 个答案:

答案 0 :(得分:2)

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

Gallery.where(user: Current.user).with_attached_photos

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

所以,就您而言:

Item.with_attached_images

答案 1 :(得分:0)

…aa,我找到了答案:

Item.reflections.keys
=> ["location", "images_attachments", "images_blobs", "taggings", "base_tags", "tag_taggings", "tags"]

由Active Storage生成的关联的名称为images_attachments,即使可以通过Item#images访问。解决方法如下:

Item.includes(:images_attachments)
  Item Load (0.6ms)  SELECT  "items".* FROM "items" LIMIT $1  [["LIMIT", 11]]
  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]]
=> #<ActiveRecord::Relation […]>