在Eager Loaded Associations上指定条件后无法获取对象

时间:2012-11-29 15:50:37

标签: ruby-on-rails ruby-on-rails-3

我有这些模特:

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

目前,我想在考试和问题答案中得到所有问题,所以我使用了在渴望加载的关联上指定条件,我在控制台中运行了这个:

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...

我现在如何获得问题对象?

1 个答案:

答案 0 :(得分: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})

请参阅Efficient ActiveRecord has_and_belongs_to_many query