【发布时间】:2017-06-22 11:39:06
【问题描述】:
以下模型星座:
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)
这些值是正确的,但是这些“(1,f) 等”的结果看起来很奇怪。键:
{"(1,f)"=>4, "(3,t)"=>2, "(2,t)"=>4, "(2,f)"=>11, "(3,f)"=>6, "(1,t)"=>4}
我将不胜感激,尤其是在结果集方面的帮助 :)。提前非常感谢!
【问题讨论】:
-
目前我只是照原样处理,将 query 更改为
Question.joins(attempts: [:answer]).group(['attempts.question_id', 'answers.correct']).count并得到{[1, false]=>4, [3, true]=>2, [2, true]=>4, [2, false]=>11, [3, false]=>6, [1, true]=>4}。不完美,但可以使用。仍然需要更酷的解决方案 ;) ...
标签: ruby-on-rails ruby activerecord arel