访问关系时避免eager_loading

时间:2015-05-06 14:04:03

标签: ruby-on-rails activerecord rails-activerecord

我的问题是我使用此查询:

@questions = Question.includes(:answer).joins('LEFT OUTER JOIN answers ON answers.question_id = questions.id AND answers.user_id= 1').select('answers.*, questions.*')

然后它产生这两个mysql查询。问题是第二个查询为每个用户提取答案。

 1.Question Load (2.7ms)  SELECT answers.*, questions.* FROM "questions" LEFT OUTER JOIN answers ON answers.question_id = questions.id AND answers.user_id= 1
 2.Answer Load (0.8ms)  SELECT "answers".* FROM "answers" WHERE "answers"."question_id" IN (2, 3, 4, 5, 6, 7, 8, 1)

1 个答案:

答案 0 :(得分:1)

第二个查询获取的答案不是针对每个用户。它为所有问题提取它们(查看查询中的条件)。如果您想避免它,请删除includes或尝试添加here所述的条件。