如何限制ActiveRecord查询,然后运行"其中"条款?

时间:2016-06-13 23:32:57

标签: sql ruby-on-rails ruby postgresql activerecord

我正在尝试查找调查的回复,将响应次数限制为用户计划中指定的限制,然后对于每个选项,我想查找有多少回复。我当前的查询如下所示:

Response.joins(choice: { question: :survey })
    .where(surveys: { id:survey.id })
    .limit(plan.response_limit)
    .where(choice: object)

但是,此查询运行"其中"子句,然后限制查询。有人可以告诉我如何写一个符合我想要的查询吗?

编辑:

我发布的查询产生以下SQL:

 SELECT  "responses".* FROM "responses" 
 INNER JOIN "choices" ON "choices"."id" = "responses"."choice_id" 
 INNER JOIN "questions" ON "questions"."id" = "choices"."question_id" 
 INNER JOIN "surveys" ON "surveys"."id" = "questions"."survey_id" 
 WHERE "surveys"."id" = 1 AND "responses"."choice_id" = 1 
 LIMIT 5000

编辑2:SQL格式

1 个答案:

答案 0 :(得分:0)

您可以使用from方法从子查询中选择:

subquery = Response.joins(choice: { question: :survey })
  .where(surveys: { id:survey.id })
  .limit(plan.response_limit)

responses = Response.from(subquery, :resp)
  .where(choice: object)

我不能100%确定Rails如何处理幕后的子查询,所以你可能不得不将其调整为类似的东西:

responses = Response.from(subquery)
  .where("resp.choice_id = ?", object)