简体   繁体   中英

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

也许

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM