Sha256: 30ad9e645863a0bc75ac51382512ac2746504797d0b24a8ca7366f6b9d10a2cd

Contents?: true

Size: 813 Bytes

Versions: 10

Compression:

Stored size: 813 Bytes

Contents

# frozen_string_literal: true

require "n1_loader/ar_lazy_preload"

require_relative 'context/setup_ar_lazy'
require_relative 'context/setup_database'

class User < ActiveRecord::Base
  has_many :payments

  n1_optimized :payments_total do |users|
    total_per_user = Payment.group(:user_id).where(user: users).sum(:amount).tap { |h| h.default = 0 }

    users.each do |user|
      total = total_per_user[user.id]
      fulfill(user, total)
    end
  end
end

class Payment < ActiveRecord::Base
  belongs_to :user

  validates :amount, presence: true
end

fill_database

# Has N+1
p User.all.map { |user| user.payments.sum(&:amount) }

# Has no N+1 and loads only required data
p User.preload_associations_lazily.map(&:payments_total)
# or
ArLazyPreload.config.auto_preload = true
User.all.map(&:payments_total)

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
n1_loader-1.7.2 examples/ar_lazy_integration.rb
n1_loader-1.7.1 examples/ar_lazy_integration.rb
n1_loader-1.7.0 examples/ar_lazy_integration.rb
n1_loader-1.6.6 examples/ar_lazy_integration.rb
n1_loader-1.6.5 examples/ar_lazy_integration.rb
n1_loader-1.6.4 examples/ar_lazy_integration.rb
n1_loader-1.6.3 examples/ar_lazy_integration.rb
n1_loader-1.6.2 examples/ar_lazy_integration.rb
n1_loader-1.6.1 examples/ar_lazy_integration.rb
n1_loader-1.6.0 examples/ar_lazy_integration.rb