Ruby 关于 Rails:如何在单个 SQL 查询中 select 父模型的所有子模型以及这些子模型的活动存储附件。活动记录

Ruby On Rails: How to select all children of a parent model and the Active Storage attachments of those children, in a single SQL query. Active Record

我正在寻找可以为我执行此操作的单个 SQL 查询,这样我就不必对数据库执行太多请求。我想要 select 模型的所有子项以及属于子模型的活动存储附件。

class Category < ApplicationRecord
  has_many :infographics, dependent: :destroy
  has_many :videos, dependent: :destroy
  has_many :pdfs, dependent: :destroy


private 

def create_resources
    sorted_resources = (self.pdfs.with_attached_document + self.videos +  self.infographics.with_attached_photo).sort_by(&:created_at).reverse
end

end

我想收集我的类别模型的所有 pdf、信息图表和视频子项。模型 PDF 和信息图表附加了活动存储项目,因此我想在此查询中包含这些项目,这样我就不会提出太多请求。

有人知道我如何在一个请求中写这个吗?

非常感谢您的帮助。

您可以直接查询与您的类别相关的 ActiveStorage 附件。 用一个查询做你想做的事情的一种方法可能是:

def create_resources
  sorted_resources = ActiveStorage::Attachment.
    where(record_type: class.name, record_id: id).
    order(created_at: :desc)
end

这样您就可以使用一个查询将它们全部排序。请注意,链中的最后一个方法将使用 ruby 对它们进行排序。相反,通过使用 order 方法,您告诉 ActiveRecord 也将您的结果按顺序排列。