【问题标题】:Include Active Storage attachments in Active Record query在 Active Record 查询中包含 Active Storage 附件
【发布时间】:2019-03-24 22:13:38
【问题描述】:

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

class Item < ApplicationRecord
  has_many_attached :images
end

我想使用ActiveRecord::QueryMethods.includes 来急切加载images,这是带有has_many 的非常标准的Rails 东西,但是:

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?")

知道如何让它工作吗?

【问题讨论】:

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


    【解决方案1】:

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

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

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

    所以,在你的情况下:

    Item.with_attached_images
    

    【讨论】:

    【解决方案2】:

    ……我找到了答案:

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

    活动存储生成的关联的名称是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 […]>
    

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-29
      • 1970-01-01
      • 2016-03-15
      相关资源
      最近更新 更多