From 9aa04315febfb37b50f52471a2837c40313a2d5f Mon Sep 17 00:00:00 2001
From: Ryuta Kamizono <kamipo@gmail.com>
Date: Tue, 18 Jul 2017 10:39:09 +0900
Subject: Fix unscoping `default_scope` for `Preloader`

---
 .../lib/active_record/associations/preloader/association.rb  | 12 +++++++++++-
 activerecord/test/cases/scoping/default_scoping_test.rb      |  2 ++
 2 files changed, 13 insertions(+), 1 deletion(-)

diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb
index 85343040db..698fd29beb 100644
--- a/activerecord/lib/active_record/associations/preloader/association.rb
+++ b/activerecord/lib/active_record/associations/preloader/association.rb
@@ -114,8 +114,18 @@ module ActiveRecord
             @reflection_scope ||= reflection.scope_for(klass)
           end
 
+          def klass_scope
+            current_scope = klass.current_scope
+
+            if current_scope && current_scope.empty_scope?
+              klass.unscoped
+            else
+              klass.default_scoped
+            end
+          end
+
           def build_scope
-            scope = klass.default_scoped
+            scope = klass_scope
 
             if reflection.type
               scope.where!(reflection.type => model.base_class.sti_name)
diff --git a/activerecord/test/cases/scoping/default_scoping_test.rb b/activerecord/test/cases/scoping/default_scoping_test.rb
index 83f3868f3f..a8c79628e7 100644
--- a/activerecord/test/cases/scoping/default_scoping_test.rb
+++ b/activerecord/test/cases/scoping/default_scoping_test.rb
@@ -405,6 +405,8 @@ class DefaultScopingTest < ActiveRecord::TestCase
       assert_equal post, Post.joins(:special_comments).find(post.id)
       assert_equal comments, Post.joins(:special_comments).find(post.id).special_comments
       assert_equal comments, Post.eager_load(:special_comments).find(post.id).special_comments
+      assert_equal comments, Post.includes(:special_comments).find(post.id).special_comments
+      assert_equal comments, Post.preload(:special_comments).find(post.id).special_comments
     end
   end
 
-- 
cgit v1.2.3