aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/railties/collection_cache_association_loading.rb
blob: d57680aaaae7c64a14ea546b0525310eef758473 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# frozen_string_literal: true

module ActiveRecord
  module Railties # :nodoc:
    module CollectionCacheAssociationLoading #:nodoc:
      def setup(context, options, as, block)
        @relation = relation_from_options(options)

        super
      end

      def relation_from_options(cached: nil, partial: nil, collection: nil, **_)
        return unless cached

        relation = partial if partial.is_a?(ActiveRecord::Relation)
        relation ||= collection if collection.is_a?(ActiveRecord::Relation)

        if relation && !relation.loaded?
          relation.skip_preloading!
        end
      end

      def collection_without_template(*)
        @relation.preload_associations(@collection) if @relation
        super
      end

      def collection_with_template(*)
        @relation.preload_associations(@collection) if @relation
        super
      end
    end
  end
end