Which Config File Takes Precedence In Rails - config/application.rb or config/environments/#{RAILS_ENV}.rb?

Viewed 529

In rails config, you can put configuration settings in either config/application.rb or config/environments/#{production|staging|development}.rb When faced with conflicting configuration options, which file's config option is taken as the winner?

2 Answers

Environment-specific config takes precedence over application.rb. You can see this in the docs for Rails::Application. The initial load (point 3) happens in application.rb, and environments have the chance to override in point 5.

Booting process
The application is also responsible for setting up and executing the booting process. From the moment you require “config/application.rb” in your app, the booting process goes like this:

1)  require "config/boot.rb" to set up load paths
2)  require railties and engines
3)  Define Rails.application as "class MyApp::Application < Rails::Application"
4)  Run config.before_configuration callbacks
5)  Load config/environments/ENV.rb
6)  Run config.before_initialize callbacks
7)  Run Railtie#initializer defined by railties, engines and application.
    One by one, each engine sets up its load paths, routes and runs its config/initializers/* files.
8)  Custom Railtie#initializers added by railties, engines and applications are executed
9)  Build the middleware stack and run to_prepare callbacks
10) Run config.before_eager_load and eager_load! if eager_load is true
11) Run config.after_initialize callbacks

Source: https://api.rubyonrails.org/classes/Rails/Application.html

config/application.rb trumps all the configuration options. Did a quick test, pp "application" in config/application.rb and pp "environment" in config/environments/development.rb. Also put 2 conflicting config options.

Discovered that the environment config file is loaded first allowing for the configurations in application.rb to override and be the final word for configurations.

Related