dace
dace

Reputation: 6363

Query for only nested associated records

I have the follow set up in my models:

class Project < ApplicationRecord
  has_many :plans
end

class Plan < ApplicationRecord
  belongs_to :project
  has_many :documents
end

class Document < ApplicationRecord
  belongs_to :plan
end

I'm trying to make a query in which I can easily return all nested associated records. For example, I want to be able to do something like: Project.documents and get all documents for a project. I've tried this with an includes like so:

Project.includes({plans: [:documents]})

but that doesn't appear to give me what I want when I call Project.documents. I really only want all documents for a project, so don't really need to include plans. Is there an easy way todo this in Rails 6?

Upvotes: 2

Views: 40

Answers (1)

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

The relationship between a document and a plan goes first through project, so you can use joins, specifying that a document belongs to a plan, and that a plan belongs to a project. After that you can filter the rows by selecting the plans (whose document belongs to) having the project_id equals ...:

Document.joins(plan: :project).where(plans: { project_id: ... })

Upvotes: 2

Related Questions