anywhereseason
anywhereseason

Reputation: 233

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. I want to select all children of a model and the active storage attachments belonging to the children models.

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 . 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.

Does anyone have any idea about how i could write this in a single request?

Thank you so much for your help.

Upvotes: 0

Views: 302

Answers (1)

Kostas Sklias
Kostas Sklias

Reputation: 51

You could directly query ActiveStorage attachments that relate to your category. 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. Instead, by using the order method you tell ActiveRecord to also bring your results in order.

Upvotes: 1

Related Questions