diff --git a/graphql-preload.gemspec b/graphql-preload.gemspec index c2bd62d..1be29c7 100644 --- a/graphql-preload.gemspec +++ b/graphql-preload.gemspec @@ -21,7 +21,7 @@ Gem::Specification.new do |spec| spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] - spec.add_runtime_dependency 'activerecord', '>= 4.1', '< 6' + spec.add_runtime_dependency 'activerecord', '>= 4.1', '< 7' spec.add_runtime_dependency 'graphql', '>= 1.8', '< 2' spec.add_runtime_dependency 'graphql-batch', '~> 0.3' spec.add_runtime_dependency 'promise.rb', '~> 0.7' diff --git a/lib/graphql/preload/loader.rb b/lib/graphql/preload/loader.rb index 08182e3..582192c 100644 --- a/lib/graphql/preload/loader.rb +++ b/lib/graphql/preload/loader.rb @@ -35,7 +35,23 @@ def perform(records) end private def preload_association(records) - ActiveRecord::Associations::Preloader.new.preload(records, association, preload_scope) + preloader = ActiveRecord::Associations::Preloader.new.preload(records, association, preload_scope).first + return unless preload_scope + return if Gem::Version.new(ActiveRecord::VERSION::STRING) < Gem::Version.new("6.0.0") + + # See https://github.com/rails/rails/issues/36638 for details + # Solution adapted from https://gist.github.com/palkan/03eb5306a1a3e8addbe8df97a298a466 + if preloader.is_a?(::ActiveRecord::Associations::Preloader::AlreadyLoaded) + raise ArgumentError, + "Preloading association twice is not possible. " \ + "To resolve this add `preload #{association.inspect}` to the GraphQL field definition." + end + + # this commit changes the way preloader works with scopes + # https://github.com/rails/rails/commit/2847653869ffc1ff5139c46e520c72e26618c199#diff-3bba5f66eb1ed62bd5700872fcd6c632 + preloader.send(:owners).each do |owner| + preloader.send(:associate_records_to_owner, owner, preloader.records_by_owner[owner] || []) + end end private def preload_scope