diff --git a/README.md b/README.md index ea6fa08..c8c0d02 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1568 TILs and counting..._ +_1569 TILs and counting..._ See some of the other learning resources I work on: - [Ruby Operator Lookup](https://www.visualmode.dev/ruby-operators) @@ -1009,6 +1009,7 @@ See some of the other learning resources I work on: - [Hash Slicing](rails/hash-slicing.md) - [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md) - [Include Devise Helpers In Your Controller Tests](rails/include-devise-helpers-in-your-controller-tests.md) +- [Inspect Configuration Of Database Connection](rails/inspect-configuration-of-database-connection.md) - [Inspect Previous Changes To ActiveRecord Object](rails/inspect-previous-changes-to-activerecord-object.md) - [Link To The Current Page With Query Params](rails/link-to-the-current-page-with-query-params.md) - [List All Installable Rails Versions](rails/list-all-installable-rails-versions.md) diff --git a/rails/inspect-configuration-of-database-connection.md b/rails/inspect-configuration-of-database-connection.md new file mode 100644 index 0000000..6705f49 --- /dev/null +++ b/rails/inspect-configuration-of-database-connection.md @@ -0,0 +1,45 @@ +# Inspect Configuration Of Database Connection + +There are a lot of factors that can effect the database configuration values. + +- What are the settings in each environment in `config/database.yml`? +- Is there any dynamic ERB code in `config/database.yml`? +- Is `DATABASE_URL` set in the current environment? +- Is any other code overriding these settings? + +To check the current _configuration hash_ for the database connection at +runtime, we can run the following statement: + +```ruby +> ActiveRecord::Base.connection.pool.db_config.configuration_hash +=> +{:adapter=>"postgresql", + :encoding=>"unicode", + :host=>"::1", + :user=>"postgres", + :password=>"postgres", + :pool=>5, + :database=>"still_development", + :port=>9875} +``` + +In this case, I'm running the statement from the Rails console of my app's +development environment. + +I could even access and print these values as part of debugging in a production +environment with a rake task: + +```ruby +# In lib/tasks/debug.rake +namespace :debug do + task :db_config => :environment do + puts "==== Database Configuration Debug ====" + puts "DATABASE_URL: #{ENV['DATABASE_URL']}" + puts "Active Record Config: #{ActiveRecord::Base.connection.pool.db_config.configuration_hash}" + puts "Raw ENV dump:" + ENV.sort.each { |k,v| puts "#{k}: #{v}" if k.include?('DB') || k.include?('DATABASE') } + end +end +``` + +[source](https://api.rubyonrails.org/classes/ActiveRecord/DatabaseConfigurations/HashConfig.html)