Eager Loading N+1 issue

 <%- @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 -%>

The above code produces the following N+1 queries:

  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

How do I prevent the additionally queries after the first one since I'm using a where query inside the loop?

Thanks!

Answers


you need to do two queries manually:

@lessons = Lesson.all # i.e.
@bookmarks = Bookmark.select("bookmarks.*, DISTINCT(lesson_id)").where(user_id: current_user.id)

And then

@lessons.each do |lesson|
  ...
  bookmark = @bookmarks.detect{ |b| b.lesson_id == lesson.id }
  ...
end

Need Your Help

Delphi XE2 DataSnap Server - Log client connection user/properties

delphi http rest delphi-xe2 datasnap

I'm building an XE2 DataSnap server which will serve connections from REST clients. My DSServerClass LifeCycle property is set to 'Invocation'. What I want to do is to log the details of all client

Transparency(alpha) is removed from second run in swift

swift transparency uicolor

I am loading a sub view through the following code: