简体   繁体   English

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. 活动记录

[英]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

I am looking for a single SQL query which could do this action for me so that I don't have to do so many requests to the database.我正在寻找可以为我执行此操作的单个 SQL 查询,这样我就不必对数据库执行太多请求。 I want to select all children of a model and the active storage attachments belonging to the children models.我想 select model 的所有孩子和属于孩子模型的活动存储附件。

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

I want to collect all the pdfs, infographics and videos children of my Category model.我想收集我的类别 model 的所有 pdf、信息图表和视频子项。 The models PDFs and Infographics have active storage items attached to them, so I would like to include these in this query so that I do not make too many requests.模型 PDF 和信息图表具有附加到它们的活动存储项目,因此我想在此查询中包含这些项目,这样我就不会提出太多请求。

Does anyone have any idea about how i could write this in a single request?有谁知道我如何在一个请求中写这个?

Thank you so much for your help.非常感谢你的帮助。

You could directly query ActiveStorage attachments that relate to your category.您可以直接查询与您的类别相关的 ActiveStorage 附件。 One way do do what you want with one query could be:用一个查询做你想做的事情的一种方法可能是:

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

That way you use one query to bring them all sorted.这样,您可以使用一个查询将它们全部排序。 Note that your last method in the chain would use ruby to sort them.请注意,您在链中的最后一个方法将使用 ruby 对它们进行排序。 Instead, by using the order method you tell ActiveRecord to also bring your results in order.相反,通过使用 order 方法,您告诉 ActiveRecord 也将您的结果按顺序排列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM