mercredi 15 juin 2016

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. Could someone please tell me how to write a query that does what I want?

Edit:

The query I posted produces the following 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

Aucun commentaire:

Enregistrer un commentaire