我有3个表-一个模型QuizResult,一个模型QuizAnswers,然后是它们的可联结表(quiz_answer_quiz_results):
class QuizResult < ActiveRecord::Base
has_and_belongs_to_many :quiz_answers, :join_table => :quiz_answer_quiz_results
belongs_to :quiz
has_many :quiz_questions, through: :quiz_answers
end
class QuizAnswer < ActiveRecord::Base
belongs_to :quiz_question
has_and_belongs_to_many :quiz_results, :join_table => :quiz_answer_quiz_results
end
我希望能够通过搜索归因的quiz_answer_ids来找到QuizResult,但即使通过sql语法,我也无法弄清这种关系。
如果我问QuizResult.first.answer_ids,则朝相反的方向前进,得到[5,9):
QuizResult.first.quiz_answer_ids
QuizResult Load (2.0ms) SELECT "quiz_results".* FROM "quiz_results" ORDER BY "quiz_results"."id" ASC LIMIT 1
(4.2ms) SELECT "quiz_answers".id FROM "quiz_answers" INNER JOIN "quiz_answer_quiz_results" ON "quiz_answers"."id" = "quiz_answer_quiz_results"."quiz_answer_id" WHERE "quiz_answer_quiz_results"."quiz_result_id" = $1 [["quiz_result_id", 1]]
=> [5, 9]
已为我想做的事情quiz_answer_ids 5,9如何获取QuizResult对象?我一直在尝试各种奇怪的QuizResult.joins(:quiz_answers)或sql查询,但无济于事。
答案 0 :(得分:1)
尝试:
QuizResult.includes(:quiz_answers).where(quiz_answers: { id: [5,9] })