【发布时间】:2018-05-10 13:11:51
【问题描述】:
我在尝试使用连接编写 Rails 查询时遇到问题。
我正在构建的是根据给定试卷的各个部分对候选答案进行分组的哈希。 (注意,我有一个问题池,其中一些问题被添加到试卷的不同部分)
我已经使用地图实现了我的解决方案:
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
由于使用上述方法会创建大量在后台运行的数据库查询,因此使用起来并不健康,因此我需要使用联接。另外,我可以编写一个 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)
但是当我在 Rails 中尝试相同的方法时,我遇到了很多问题。
这是我的模型结构:
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 的新手是我的劣势,如果有人可以尝试或提出一些建议,那将非常有帮助。
【问题讨论】:
-
您能解释一下您在查询时遇到的问题吗?您需要将其转换为 activerecord 查询还是只使用原始 SQL?
-
我需要它来转换为活动记录查询
-
这里有人遇到类似问题stackoverflow.com/questions/28146848/…
标签: ruby-on-rails database activerecord