如何在Rails中创建Scope,筛选关联记录全满足条件的模型实例
解决Ruby on Rails模型Scope筛选全部关联记录的问题
你的需求是筛选出所有关联的participant的acknowledged_at字段均不为空的模型记录,当前的Scope仅能筛选出至少有一个participant满足条件的记录,可通过以下两种方式调整:
方法一:排除存在未确认participant的记录
通过子查询找出所有存在acknowledged_at为空的participant对应的主模型ID,再排除这些ID即可:
scope :completed, -> { where.not(id: ExampleParticipant.where(acknowledged_at: nil).select(:example_id)) }
逻辑说明:先定位到所有未完成确认的participant,拿到它们关联的主模型ID,最终筛选出不在这个ID列表里的主模型记录,确保剩下的主模型所有participant都已完成确认。
方法二:通过分组计数匹配确认状态
利用分组统计,确保主模型的所有participant数量等于已确认(acknowledged_at非空)的数量:
scope :completed, -> { joins(:example_participants) .group('examples.id') .having('COUNT(example_participants.id) = COUNT(example_participants.acknowledged_at)') }
逻辑说明:COUNT(example_participants.id)统计主模型关联的所有participant总数,COUNT(example_participants.acknowledged_at)仅统计acknowledged_at非空的记录数,两者相等则说明所有participant都已确认。
特殊场景处理:包含无关联participant的记录
如果需要将没有任何关联participant的主模型也纳入筛选结果,可将joins替换为left_joins(左连接):
scope :completed, -> { left_joins(:example_participants) .group('examples.id') .having('COUNT(example_participants.id) = COUNT(example_participants.acknowledged_at)') }
此时无participant的主模型,两个计数结果均为0,会被判定为符合条件。
内容的提问来源于stack exchange,提问作者Zachariah White
相关产品推荐
相关产品推荐

