Ruby on rails 包含所有关联的ActiveRecord查询

Ruby on rails 包含所有关联的ActiveRecord查询,ruby-on-rails,postgresql,activerecord,Ruby On Rails,Postgresql,Activerecord,例如,假设我有以下三张表: 事件、出席人数(联接表)和用户 Event has_many attendances and has_many users through attendances User has_many attendances and has_many events through attendances Attendance belongs_to attendance and belongs_to user 我希望能够查询所有事件,以找到x个用户都参加了哪些活动。 例如: E

例如,假设我有以下三张表: 事件、出席人数(联接表)和用户

Event has_many attendances and has_many users through attendances
User has_many attendances and has_many events through attendances
Attendance belongs_to attendance and belongs_to user
我希望能够查询所有事件,以找到x个用户都参加了哪些活动。 例如:

Event     | Users who attended Event
1               [1, 3, 4, 6, 9]
2               [1, 4, 9]
3               [3, 4, 6]
4               [2, 3, 6]
我想说
Event.by_attendent_用户(用户4、用户9)
并获取
事件:[1,2]

我一直在想一些关于连接(:Attentations)的事情。where(“attentations.user\u id IN:user\u id”)或类似的事情,但还没有完全按照预期工作。非常感谢您的任何帮助或反馈

编辑:正如@AbM所指出的,还有一些额外的细节,如果一次只有两个用户加入,那么可以使用一些小技巧来查找用户。该解决方案不起作用,因为查询的第二部分过度编写了第一部分

理想情况下,这应该能够处理任意数量的关联,尽管最基本的要求只是说它需要使用2。(目前)

此外,我希望能够将其用作范围,这意味着可以将其链接到其他范围以进一步过滤。@AbM的解决方案只有在其他过滤器链中首先调用该范围时才能使用它

user_ids = [1, 3, 5]
events = Event.joins(:attendances)
user_ids.each {|user_id| events = events.where('attendances.user_id = ?', user_id) }

# events now contains all events where all specified users attended
另一种方法是使用自定义计数:

user_ids = [4, 9]
Event.joins(:attendances).having('COUNT(CASE WHEN attendances.user_id IN (?) THEN 1 END) = ?', user_ids, user_ids.length).group(:id)

@非常聪明!最理想的情况是,我想考虑使用2个以上用户的情况,但这是目前最基本的要求,因此如果没有更好的解决方案,我很乐意使用此解决方案。:)非常感谢。这似乎不起作用。我认为
的where(attentments:{user\u id:user\u 9.id})
是过度写入初始范围并返回到原始问题:(这不允许一个用户多次参加同一个活动,因为搜索结果会因计数而变得混乱。但这是一个好的开始。我可以使用常规数组操作手动完成其余部分。我不太清楚你的意思。为什么一个用户会多次参加同一个活动?
user_ids = [4, 9]
Event.joins(:attendances).having('COUNT(CASE WHEN attendances.user_id IN (?) THEN 1 END) = ?', user_ids, user_ids.length).group(:id)