Rails 活动记录查询与“存在"的关联 [英] Rails active record querying association with 'exists'

查看:34
本文介绍了Rails 活动记录查询与“存在"的关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一款允许会员参与调查的应用(会员与 Response 之间存在一对多关系).Response 包含 member_id、question_id 和他们的答案.

I am working on an app that allows Members to take a survey (Member has a one to many relationship with Response). Response holds the member_id, question_id, and their answer.

该调查要么全部提交,要么不提交,因此如果该成员的响应表中有任何记录,则他们已经完成了调查.

The survey is submitted all or nothing, so if there are any records in the Response table for that Member they have completed the survey.

我的问题是,如何重新编写下面的查询以使其真正起作用?在 SQL 中,这将是 EXISTS 关键字的主要候选对象.

My question is, how do I re-write the query below so that it actually works? In SQL this would be a prime candidate for the EXISTS keyword.

 def surveys_completed
    members.where(responses: !nil ).count
 end 

推荐答案

您可以使用 includes 然后测试相关响应是否存在,如下所示:

You can use includes and then test if the related response(s) exists like this:

def surveys_completed
  members.includes(:responses).where('responses.id IS NOT NULL')
end

这是一种替代方法,使用 joins:

Here is an alternative, with joins:

def surveys_completed
  members.joins(:responses)
end

使用 Rails 4 的解决方案:

def surveys_completed
  members.includes(:responses).where.not(responses: { id: nil })
end

<小时>

使用 activerecord_where_assoc 的替代解决方案:这个 gem 完全符合这里的要求:使用 EXISTS 来做一个条件.它适用于最新的 Rails 4.1.


Alternative solution using activerecord_where_assoc: This gem does exactly what is asked here: use EXISTS to to do a condition. It works with Rails 4.1 to the most recent.

members.where_assoc_exists(:responses)

它还可以做得更多!

类似问题:

这篇关于Rails 活动记录查询与“存在"的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆