Slevin
Slevin

Reputation: 4222

Query records with nested relationships 2-levels deep

I have 4 models [Project, Task, TaskAssignment, User] with this relationsships:

Now I want to get all projects that have tasks that are assigned to a specific user.

My attempt:

Project
    .includes(:tasks, {:task_assignments => [:tasks, :task_assignments]})
    .where("task_assignments.user_id = #{user_id}")
    .references(:tasks) 

Throws ActiveRecord::ConfigurationError (Association named 'task_assignment' was not found on Project; perhaps you misspelled it?)

Upvotes: 2

Views: 693

Answers (2)

Slevin
Slevin

Reputation: 4222

I figured it out:

First, add this relationship to the Project model:

has_many :task_assignments, through: :tasks

Then use this query:

Project.includes(:task_assignments).where("task_assignments.user_id = #{user_id}").references(:task_assignments)

Upvotes: 2

Babar
Babar

Reputation: 1202

You should be using joins for this, anyways task_assignments belong to task. try working it like that.

Upvotes: 0

Related Questions