<%- @lessons.includes(:bookmarks).each_with_index do |lesson, index| -%>
<tr>
<td class="w6 pl">
<%- bookmark = lesson.bookmarks.where(user_id: current_user).first -%>
<%= render :partial => "student/lessons/bookmark", :locals => {:bookmark => bookmark, :lesson => lesson} %>
</td>
</tr>
<%- end -%>
上面的代码产生以下 N+1 个查询:
Bookmark Load (0.3ms) SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."lesson_id" IN (1, 2, 3, 4, 5, 6)
Bookmark Load (0.3ms) SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."lesson_id" = 1 AND "bookmarks"."user_id" = 1 LIMIT 1
Rendered student/lessons/_bookmark.html.erb (1.4ms)
Bookmark Load (0.3ms) SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."lesson_id" = 2 AND "bookmarks"."user_id" = 1 LIMIT 1
Rendered student/lessons/_bookmark.html.erb (0.6ms)
Bookmark Load (0.3ms) SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."lesson_id" = 3 AND "bookmarks"."user_id" = 1 LIMIT 1
Rendered student/lessons/_bookmark.html.erb (0.6ms)
Bookmark Load (0.3ms) SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."lesson_id" = 4 AND "bookmarks"."user_id" = 1 LIMIT 1
Rendered student/lessons/_bookmark.html.erb (0.6ms)
Bookmark Load (0.2ms) SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."lesson_id" = 5 AND "bookmarks"."user_id" = 1 LIMIT 1
Rendered student/lessons/_bookmark.html.erb (0.6ms)
Bookmark Load (0.1ms) SELECT "bookmarks".* FROM "bookmarks" WHERE "bookmarks"."lesson_id" = 6 AND "bookmarks"."user_id" = 1 LIMIT 1
由于我在循环内使用 where 查询,如何防止第一个查询之后的额外查询?
谢谢!