0

I have this use case.

Project:
  has_many :assignments

Assignment:
  has_many :assignments_users, class_name: "AssignmentsUsers"
  has_many :assignees, through: :assignments_users, source: :user

assignments_users: is simply user_id and assignment_id.

I'd like to be able to do something like this.

projects = Project.includes(:assignments, {assignments: :assginments_users}).where("assignments.assignments_users.user_id = 6")

Where if I was to access assignments from a given project in the list, I would only see assignments where one of the users assigned is a user with id 6.

is this even do able?

I was thinking maybe I make an extra has_many my_assignments, (user_id) -> { where(match_something_to_my_user_id) }

is that even possible?

Polygon Pusher
  • 2,865
  • 2
  • 27
  • 32

1 Answers1

1

Your example is pretty close to something that should work:

projects = Project.
  includes(assignments: :assignments_users).
  where(assignments_users: { user_id: 6 })

Alternatively, it might be neater to approach from the other side:

Assignment:
  belongs_to :project

User:
  has_many :assignments_users, class_name: "AssignmentsUsers"
  has_many :assignments, through: :assignments_users
  has_many :active_projects, through: :assignments, source: :project

my_user.active_projects
matthewd
  • 4,332
  • 15
  • 21
  • I'm gonna mark this as the answer but its still not 100% what I'm looking for. Maybe you can help me with the rest. The problem I have with this is that it limits the projects. Where I only wanted to limit the associations of assignments. IE: Say I have 10 projects. I want to return all 10 projects but if I say project.assignment I'd only see assignments where that condition is true. What I'm trying to prevent is an N+1 but I may not have a choice in the matter – Polygon Pusher Jul 20 '18 at 02:11
  • Ah, sorry, there aren't great options there. `includes` does use a left join, so `where("user_id = 6 OR user_id IS NULL")` could kinda do something... otherwise, I believe there are ways you can hack it using private API -- see e.g. https://stackoverflow.com/a/29963082/476979 – matthewd Jul 20 '18 at 02:44