简体   繁体   English

Rails活动记录包括条件

[英]Rails active record includes condition

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. assignments_users:仅是user_id和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. 如果要访问列表中给定项目的工作分配,我只会看到其中分配的用户之一是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) } 我在想,也许我会has_many my_assignments, (user_id) -> { where(match_something_to_my_user_id) }一个has_many my_assignments, (user_id) -> { where(match_something_to_my_user_id) }

is that even possible? 那有可能吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM