Search code examples
ruby-on-railshas-and-belongs-to-manyjoin

RoR lookup HABTM join by multiple ids


I've got 3 tables -- a model QuizResult, a model QuizAnswers and then a jointable for them (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

I want to be able to find a QuizResult by searching for attributed quiz_answer_ids and yet I can't figure out the relation, even via sql syntax.

Going in the OPPOSITE direction, if I ask QuizResult.first.answer_ids I get [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]

What I'm trying to do is given quiz_answer_ids 5,9 how can I get back a QuizResult object? I've been attempting all sorts of strange QuizResult.joins(:quiz_answers), or sql queries, but to no avail.


Solution

  • Try:

    QuizResult.includes(:quiz_answers).where(quiz_answers: { id: [5,9] })