ruby-on-railsactiverecordselect-n-plus-1

N+1 in rails relations with active records?


I have four models

  1. Group
  2. Reports
  3. Comments
  4. user

Group => has_many => Reports

Report => has_many => Comments

Comment => Belongs_to => User

When i want to show a group I do something like

 <%= @group.name %>
 <%= @group.reports.includes(:comments).each do |report| %>
      <%= report.name %>
      <% report.comments.each do |comment| %>
           <%= comment.name %>
           <%= comment.user.name %>
      <% end %>
 <% end %>

What is the best way to solve N+1 Query problems in this case ??


Solution

  • Perhaps

    @group.reports.includes(:comments => :user).each do |report|