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,但在rails guide,它说查询会做一个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 回答