N+1 in rails relations with active records?

耗尽温柔 提交于 2020-01-03 05:41:07

问题


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 ??


回答1:


Perhaps

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


来源:https://stackoverflow.com/questions/13806639/n1-in-rails-relations-with-active-records

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!