我有这个用例。
Project:
has_many :assignments
Assignment:
has_many :assignments_users, class_name: "AssignmentsUsers"
has_many :assignees, through: :assignments_users, source: :user
assignments_users: 只是user_id和Assignment_id。
我希望能够做这样的事情。
projects = Project.includes(:assignments, {assignments: :assginments_users}).where("assignments.assignments_users.user_id = 6")
如果要访问列表中给定项目的分配,则只会看到分配的用户之一是ID为6的用户的分配。
这甚至可以吗?
我在想,也许我会多赚has_many my_assignments, (user_id) -> { where(match_something_to_my_user_id) }
那有可能吗?
答案 0 :(得分:1)
您的示例非常接近应该起作用的地方:
projects = Project.
includes(assignments: :assignments_users).
where(assignments_users: { user_id: 6 })
或者,从另一侧接近可能会更整洁:
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