From 92d31b1f81fd9e4166f7970f287ed3cf34d63bd2 Mon Sep 17 00:00:00 2001 From: Eugene Kenny Date: Wed, 14 Aug 2019 02:54:13 +0100 Subject: [PATCH] Fix setting connection_specification_name on ActiveRecord::Base Since 2f8b397258b66581409b0e6537f98ea9b56e9f19, `ActiveRecord::Base` and `ApplicationRecord` use the same default `connection_specification_name` so that database connections configured on `ApplicationRecord` also apply to `ActiveRecord::Base`. However, when resolving the connection for `ApplicationRecord` we should continue to fall back to `ActiveRecord::Base` when there's no connection explicitly configured, so that setting `connection_specification_name` on `ActiveRecord::Base` affects `ApplicationRecord` and its descendants in this case as it did in previous versions. --- activerecord/lib/active_record/connection_handling.rb | 2 +- .../cases/connection_adapters/connection_handler_test.rb | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/connection_handling.rb b/activerecord/lib/active_record/connection_handling.rb index c8cefa9906..29a89762c2 100644 --- a/activerecord/lib/active_record/connection_handling.rb +++ b/activerecord/lib/active_record/connection_handling.rb @@ -204,7 +204,7 @@ def connection # Return the specification name from the current class or its parent. def connection_specification_name if !defined?(@connection_specification_name) || @connection_specification_name.nil? - return primary_class? ? "primary" : superclass.connection_specification_name + return self == Base ? "primary" : superclass.connection_specification_name end @connection_specification_name end diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb index 843242a897..f2fa6f12cf 100644 --- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb @@ -375,6 +375,8 @@ class MyClass < ApplicationRecord end def test_connection_specification_name_should_fallback_to_parent + Object.send :const_set, :ApplicationRecord, ApplicationRecord + klassA = Class.new(Base) klassB = Class.new(klassA) klassC = Class.new(MyClass) @@ -387,6 +389,12 @@ def test_connection_specification_name_should_fallback_to_parent klassA.connection_specification_name = "readonly" assert_equal "readonly", klassB.connection_specification_name + + ActiveRecord::Base.connection_specification_name = "readonly" + assert_equal "readonly", klassC.connection_specification_name + ensure + Object.send :remove_const, :ApplicationRecord + ActiveRecord::Base.connection_specification_name = "primary" end def test_remove_connection_should_not_remove_parent