Question

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

  • Tasks n:m Users through TaskAssignment
  • Projects hasMany Tasks

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?)

Was it helpful?

Solution

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)

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top