diff --git a/activerecord/lib/active_record/database_configurations.rb b/activerecord/lib/active_record/database_configurations.rb index 2b69304788..0c4f478876 100644 --- a/activerecord/lib/active_record/database_configurations.rb +++ b/activerecord/lib/active_record/database_configurations.rb @@ -79,10 +79,12 @@ module ActiveRecord # If the application has multiple databases +find_db_config+ will return # the first DatabaseConfig for the environment. def find_db_config(env) - configurations.find do |db_config| - db_config.env_name == env.to_s || - (db_config.for_current_env? && db_config.name == env.to_s) - end + configurations + .sort_by { |db_config| db_config.for_current_env? ? 0 : 1 } + .find do |db_config| + db_config.env_name == env.to_s || + (db_config.for_current_env? && db_config.name == env.to_s) + end end # Returns the DatabaseConfigurations object as a Hash. diff --git a/activerecord/test/cases/database_configurations_test.rb b/activerecord/test/cases/database_configurations_test.rb index 3de9618a1f..527a18bc57 100644 --- a/activerecord/test/cases/database_configurations_test.rb +++ b/activerecord/test/cases/database_configurations_test.rb @@ -61,6 +61,24 @@ class DatabaseConfigurationsTest < ActiveRecord::TestCase assert_equal "primary", config.name end + def test_find_db_config_prioritize_db_config_object_for_the_current_env + config = ActiveRecord::DatabaseConfigurations.new({ + "primary" => { + "adapter" => "randomadapter" + }, + ActiveRecord::ConnectionHandling::DEFAULT_ENV.call => { + "primary" => { + "adapter" => "sqlite3", + "database" => ":memory:" + } + } + }).find_db_config("primary") + + assert_equal "primary", config.name + assert_equal ActiveRecord::ConnectionHandling::DEFAULT_ENV.call, config.env_name + assert_equal ":memory:", config.database + end + def test_to_h_turns_db_config_object_back_into_a_hash_and_is_deprecated configs = ActiveRecord::Base.configurations assert_equal "ActiveRecord::DatabaseConfigurations", configs.class.name