Last active
December 21, 2015 19:09
-
-
Save finist/6352009 to your computer and use it in GitHub Desktop.
n+1 problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User < ActiveRecord::Base | |
has_many :mails | |
def messages_for_recipient(user) | |
mails.where(user_id: user.id).map(&:messages).flatten | |
end | |
end | |
class Mail < ActiveRecord::Base | |
has_many :messages | |
end | |
class UserController < ApplicationController | |
def index | |
@users = User.includes(:messages) | |
end | |
end | |
#index.html.haml | |
- @users.each do |user| | |
= user.messages.count # дополнительного запроса нет | |
= render partial: messages, collection: user.messages_for_recipient(user) # дополнительный sql запрос (problem!) | |
#_messages.html.haml | |
message.id | |
message.subject | |
message.body |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment