2

私はこれらのモデルを持っています:

class Question
  has_many :answers
end

class Answer
  belongs_to :question
end

class Exam
  belongs_to :general_exam
  belongs_to :user
  has_many :questions, through: :exam_questions
end

class ExamQuestion
  belongs_to :exam
  belongs_to :question
end

現在、試験のすべての質問と質問の回答を取得したいので、Specifying Conditions on Eager Loaded Associationsを使用し、コンソールでこれを実行しました。

exam = Exam.find(16)
questions = Question.includes(:answers).where("id = ?", exam.question_ids)

実行後のコンソール出力questions = ...:

SELECT "questions".id FROM "questions" INNER JOIN "exam_questions" ON "questions"."id" = "exam_questions"."question_id" WHERE "exam_questions"."exam_id" = 16 ORDER BY questions.created_at DESC
  Question Load (0.8ms)  SELECT "questions".* FROM "questions" WHERE (id = 170,162,160) ORDER BY questions.created_at DESC
=> #<ActiveRecord::Relation:0x4c07ebc>

最初の奇妙なことは、クエリで見た、それはINNER JOINを実行しましたが、レールガイドでは、クエリがLEFT OUTER JOINを作成すると言いました。なぜこれが違うのかわかりません。

次に、 で質問オブジェクトを取得したいので、次のようquestionsに実行しました。

questions.each do |q|
  puts q.content
end

エラーが返されました:

SELECT "questions".* FROM "questions" WHERE (id = 170,162,160) ORDER BY questions.created_at DESC
ActiveRecord::StatementInvalid: PG::Error: ERROR:  argument of WHERE must be type boolean, not type record
LINE 1: SELECT "questions".* FROM "questions"  WHERE (id = 170,162,1...

質問オブジェクトを取得するにはどうすればよいですか?

4

1 に答える 1

2

where句が間違っているようです。試す:

where(:id => exam.question_ids)

文字列バージョン「id = ?」を指定すると、データベース アダプタはそれを in-clause に変換しません。ハッシュ バージョンを指定すると、データベース アダプタは値が配列であることを認識し、in を使用します。

おそらく、より効率的な方法は、問題に別の方法でアプローチすることです。

class Question
  has_many :exam_questions
end

questions = Question.joins(:exam_questions).where(:exam_questions => {:exam_id => 16})

効率的な ActiveRecord の has_and_belongs_to_many クエリを参照してください

于 2012-11-29T16:08:22.987 に答える