为什么我的代码会产生额外的查询?

时间:2016-11-27 19:31:18

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

我的控制器中有以下代码:

@unanswered_questions = Question.unanswered_with_tag(params[:tag_id]).paginate(per_page: 10, page: params[:page])

在我的Question模型中调用此方法:

def self.unanswered_with_tag id
  joins(:taggings).where(taggings: { tag_id: id }).where(questions: { num_answers: 0})
end

我希望有一个sql查询可以获取该页面上的前10个未答复的问题,但我的日志显示了2个查询:

 Question Load (0.4ms)  SELECT  "questions".* FROM "questions"  
 INNER JOIN "taggings" ON "taggings"."question_id" = "questions"."id" 
 WHERE "taggings"."tag_id" = $1 AND "questions"."num_answers" = $2 
 ORDER BY "questions"."id" ASC LIMIT $3 OFFSET $4  
 [["tag_id", 3], ["num_answers", 0], ["LIMIT", 1], ["OFFSET", 0]]

^^注意LIMIT 1部分。

第二个问题:

 SELECT  "questions".* FROM "questions" INNER JOIN "taggings"  
   ON "taggings"."question_id" = "questions"."id" 
   WHERE "taggings"."tag_id" = $1 AND "questions"."num_answers" = $2 
   LIMIT $3 OFFSET $4  
   [["tag_id", 3], ["num_answers", 0], ["LIMIT", 10], ["OFFSET", 0]]

哪个有限制10.

为什么会出现这种情况?

1 个答案:

答案 0 :(得分:0)

您是否在视图中运行代码,检查@unanswered_questions是否有任何行(例如#exists?)以显示值?