[英]How do I limit an ActiveRecord query, then run a “where” clause?
I'm trying to find responses for a survey, limiting the number of responses to the limit specified on the user's plan, then for each choice, I want to find how many responses there are. 我正在尝试查找调查的答复,将答复的数量限制为用户计划中指定的限制,然后针对每个选择,我想查找有多少答复。 My current query looks like this: 我当前的查询如下所示:
Response.joins(choice: { question: :survey })
.where(surveys: { id:survey.id })
.limit(plan.response_limit)
.where(choice: object)
However, this query runs the "where" clauses, then limits the query. 但是,此查询运行“ where”子句, 然后限制查询。 Could someone please tell me how to write a query that does what I want? 有人可以告诉我如何编写符合我要求的查询吗?
Edit: 编辑:
The query I posted produces the following SQL: 我发布的查询产生以下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
Edit 2: SQL formatting 编辑2:SQL格式
You can use the from
method to SELECT from a subquery: 您可以使用from
方法从子查询中进行SELECT:
subquery = Response.joins(choice: { question: :survey })
.where(surveys: { id:survey.id })
.limit(plan.response_limit)
responses = Response.from(subquery, :resp)
.where(choice: object)
I'm not 100% sure how Rails deals with subqueries behind the scenes, so you might have to tweak that into something like this instead: 我不是100%不确定Rails如何处理后台的子查询,因此您可能不得不将其调整为类似以下内容:
responses = Response.from(subquery)
.where("resp.choice_id = ?", object)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.