问题
I have four models
- Group
- Reports
- Comments
- 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