Sha256: be7fcd756f034c9a349d84dac57c38c4bb8d44f8b81253558d274bde7142e761

Contents?: true

Size: 929 Bytes

Versions: 3

Compression:

Stored size: 929 Bytes

Contents

module ActiveRecord
  module Associations
    class Preloader
      class CountLoader < SingularAssociation
        def association_key_name
          reflection.foreign_key
        end

        def owner_key_name
          reflection.active_record_primary_key
        end

        private

        def preload(preloader)
          associated_records_by_owner(preloader).each do |owner, associated_records|
            owner.association(reflection.name).target = associated_records.first.to_i
          end
        end

        def load_slices(slices)
          @preloaded_records = slices.flat_map { |slice|
            records_for(slice)
          }

          @preloaded_records.first.map { |key, count|
            [count, key]
          }
        end

        def query_scope(ids)
          scope.where(association_key.in(ids)).group(association_key_name).count(association_key_name)
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
activerecord-precount-0.5.1 lib/active_record/associations/preloader/count_loader.rb
activerecord-precount-0.5.0 lib/active_record/associations/preloader/count_loader.rb
activerecord-precount-0.4.3 lib/active_record/associations/preloader/count_loader.rb