以下模型星座:
class Attempt < ApplicationRecord
belongs_to :user
belongs_to :answer
belongs_to :question
end
class Answer < ApplicationRecord
belongs_to :question
end
class Question < ApplicationRecord
has_many :answers
has_many :attempts
end
一个问题有几个答案,其中一个被标记为正确(列correct
)。用户试图猜出问题的正确答案。
挑战:我想知道每个问题的用户,尝试成功的次数(选择的正确答案)以及失败的次数,而不会针对数据库触发多次/多次查询。
让我最接近满意答案的是Question.joins(attempts: [:answer]).group('(attempts.question_id, answers.correct)').count
(到目前为止忽略那里的用户)。结果SQL:
SELECT COUNT(*) AS count_all, (attempts.question_id, answers.correct) AS attempts_question_id_answers_correct FROM "questions" INNER JOIN "attempts" ON "attempts"."question_id" = "questions"."id" INNER JOIN "answers" ON "answers"."id" = "attempts"."answer_id" GROUP BY (attempts.question_id, answers.correct)
这些值是正确的,但结果看起来很奇怪,这些&#34;(1,f)等。&#34;键:
{"(1,f)"=>4, "(3,t)"=>2, "(2,t)"=>4, "(2,f)"=>11, "(3,f)"=>6, "(1,t)"=>4}
我很感激任何帮助,尤其是结果集:)。非常感谢提前!
答案 0 :(得分:0)
你试过这个:
Question.joins(attempts: [:answer]).select("attempts.question_id as question_id, answers.correct as correct_answer").group('(attempts.question_id, answers.correct)').count