You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails查询优化:用Joins实现候选答案按试卷章节分组

如何用Rails Joins优化按章节分组候选答案的查询?

我最近在写Rails查询时遇到了瓶颈——需要把候选答案(candidate_answers)按指定试卷(question_paper)的章节(sections)分组,生成对应的哈希结构。背景是我们有一个问题池,部分问题会被分配到试卷的不同章节中。

最开始我用map方法实现了需求,代码如下:

section_question_hash = {}
exam_candidate.exam.question_paper.sections.includes(:questions).each do |section|
  if section.questions.present?
    section_question_hash[section] = candidate_answers.where(question_id: section.questions.map(&:id))
  end
end

但这段代码会在后台触发大量的数据库查询,性能实在太差了。所以我想改用joins来优化查询效率,并且已经写出了对应的SQL语句:

select b.name, group_concat(c.id) 
from sections b 
left join question_papers_questions a on a.section_id = b.id 
left join candidate_answers c on a.question_id = c.question_id 
where a.question_paper_id = 3 and c.exam_candidate_id = 4 
group by (b.name)

可当我尝试把这段SQL转换成Rails的ActiveRecord查询时,却卡壳了,试了好多次都没成功。

下面是我的模型关联结构,供大家参考:

class ExamCandidate < ActiveRecord::Base
  belongs_to :exam
  belongs_to :candidate
  has_many :candidate_answers, dependent: :delete_all
  accepts_nested_attributes_for :candidate_answers
end

class Exam < ActiveRecord::Base
  has_many :exam_candidates, dependent: :destroy
  has_many :candidates, through: :exam_candidates
  belongs_to :question_paper
end

class QuestionPaper < ActiveRecord::Base
  has_many :exams, dependent: :nullify
  has_many :exam_candidates, through: :exams
  has_many :questions, through: :question_papers_questions
  has_many :question_papers_questions
  has_many :sections, dependent: :destroy
end

class QuestionPapersQuestion < ActiveRecord::Base
  belongs_to :question
  belongs_to :question_paper
  belongs_to :section
end

class Question < ActiveRecord::Base
  has_many :candidate_answers, through: :answers
  has_many :exams, through: :question_papers
  has_many :exam_candidates, through: :exams
  has_many :question_papers_questions
  has_many :question_papers, through: :question_papers_questions
end

class Section < ActiveRecord::Base
  belongs_to :question_paper
  has_many :questions, through: :question_papers_questions
  has_many :question_papers_questions
end

class CandidateAnswer < ActiveRecord::Base
  belongs_to :exam_candidate
  belongs_to :question
end

作为Rails新手,我已经折腾了好几个小时了还是没头绪,真心希望有大佬能给我一些指导或者解决方案,谢谢大家!

内容的提问来源于stack exchange,提问作者rails_newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:00:56