Skip to content

Instantly share code, notes, and snippets.

@finist
Last active December 21, 2015 19:09
Show Gist options
  • Save finist/6352009 to your computer and use it in GitHub Desktop.
Save finist/6352009 to your computer and use it in GitHub Desktop.
n+1 problem
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