In Rails, when DATABASE_URL is set and config/database.yml also defines that environment, which values win and how are they merged?
answer
- URL on top, YAML underneath
- unset URL parts keep YAML values
- query string turns into config keys
- CACHE_DATABASE_URL for named entries
- url: in YAML skips the merge
basics
~20 sRails merges DATABASE_URL on top of the current environment's primary entry: the URL's adapter, host, port, credentials and database replace the YAML values, YAML keys the URL leaves out (such as max_connections) survive, and query parameters become extra keys.
solid answer
~40 sFor the running environment, Active Record looks for a URL variable per database entry: `PRIMARY_DATABASE_URL` or `DATABASE_URL` for `primary`, and `<NAME>_DATABASE_URL` (say `CACHE_DATABASE_URL`) for other entries. It parses the URL into a hash (scheme to `adapter`, plus `host`, `port`, `username`, `password`, `database`) and merges that hash over the YAML entry. Parts the URL does not contain are dropped before the merge, so they never blank out a YAML value, and keys such as `max_connections` or `migrations_paths` stay. Query parameters become keys too, so `?sslmode=require` lands in the config. Two exceptions: an entry that already has its own `url:` key is not merged with the variable, and if the YAML has no block for the environment, `DATABASE_URL` alone builds the primary configuration.
go deeper
Remember that DATABASE_URL and database.yml are combined, not either-or, and that the URL supplies host, credentials and database name.
Walk through the merge: per-entry variable names, URL keys over YAML keys, blank parts dropped, query parameters added, and the url: exception.
Use per-entry variables to move one database of a multi-database app, and check the merged hash in production rather than trusting the file.
Decide which settings belong in the platform's URL and which stay in the repository, so a credential rotation never requires a code change.
## Why Rails merges instead of choosing Hosting platforms usually hand an app a single connection string, while `config/database.yml` holds settings that are not about *where* the database is: the pool ceiling, the encoding, `migrations_paths`, `replica: true`. Rails lets both coexist: the **URL says where and who**, the **YAML says how**. The merge happens when Active Record builds its database configurations for the current environment. ## The merge, step by step 1. Rails loads `config/database.yml` (ERB, then YAML) and builds one configuration per entry. A two-tier block becomes one entry named `primary`. 2. For each entry **in the current environment only**, it looks up an environment variable. The name is the entry name upper-cased plus `_DATABASE_URL`; for `primary`, `PRIMARY_DATABASE_URL` is checked first and plain `DATABASE_URL` second. 3. If a variable is found, `ConnectionUrlResolver` parses it: the scheme becomes `adapter`, and the user, password, host, port and path become `username`, `password`, `host`, `port` and `database`. Query parameters are added as keys. 4. Blank parts are removed from that hash (`compact_blank`), so a URL with no password does not erase the YAML password. 5. The URL hash is merged **over** the YAML hash: same-named keys take the URL's value, and every other YAML key survives. 6. String values for `replica` and `database_tasks` from a query string are turned into booleans, so `?replica=true` works. ## Which variable feeds which entry | database.yml entry (production) | Variable Rails reads | |---|---| | `primary` (or a two-tier block) | `PRIMARY_DATABASE_URL`, then `DATABASE_URL` | | `cache` | `CACHE_DATABASE_URL` | | `queue` | `QUEUE_DATABASE_URL` | | `cable` | `CABLE_DATABASE_URL` | | `primary_replica` | `PRIMARY_REPLICA_DATABASE_URL` | `DATABASE_URL` itself is only ever applied to the `primary` entry. The generated PostgreSQL template says the same thing in its comments. ## Worked example: a payroll service ```yaml production: adapter: postgresql host: db-old.internal database: payroll_production max_connections: 10 ``` With `DATABASE_URL=postgres://payroll:[email protected]:5432/payroll_v2?sslmode=require`, the resulting configuration has: - `adapter: postgresql`, `host: db-new.internal`, `port: 5432`, `username: payroll`, `password: secret`, `database: payroll_v2`, all from the URL; - `sslmode: "require"` from the query string; - `max_connections: 10`, kept from the YAML because the URL said nothing about it. You can check what a running process actually uses with `ActiveRecord::Base.connection_db_config.configuration_hash`, which is easier than reasoning about the merge in your head. ## Edge cases worth knowing - **An entry with its own `url:`** is built as a URL configuration from the start, and the environment variable is **not** merged into it. Teams who write `url: <%= ENV["DATABASE_URL"] %>` get the same result explicitly. - **No block for the environment** (or no `database.yml` at all): `DATABASE_URL` alone creates the primary configuration. - **Other environments are untouched.** The variable merges into the entry of whatever `RAILS_ENV` the process runs under, so a `DATABASE_URL` exported in a developer's shell also redirects a test run. - **Query values are strings.** `?max_connections=20` arrives as `"20"`; Active Record converts the numeric settings it reads, but a custom key you read yourself needs the same care. - **Precedence inside the URL:** query parameters win over the parts of the URL they share a name with, because the resolver reverse-merges the parts under the query hash. ## A typical production layout Most deployments end up with a split like this one: - The **platform or secret store** sets `DATABASE_URL` (and, in a multi-database app, `CACHE_DATABASE_URL`, `QUEUE_DATABASE_URL` and friends). Rotating a password or moving to a new host changes only those variables. - **`database.yml` in the repository** keeps the keys that describe behaviour: `max_connections`, `encoding`, `migrations_paths`, `replica: true`, timeouts. They change with code review, not with the infrastructure. - **Development and test** usually carry no URL at all and rely on the YAML database names, which keeps a laptop independent of any shared server. Because the URL is merged over the YAML, the two halves never fight: the YAML entry can even keep a `host:` for local use, and production's URL simply replaces it. ## What to say in an interview The short version: the URL replaces the location and credentials, the YAML keeps everything else, and only the primary entry listens to `DATABASE_URL`. Naming `CACHE_DATABASE_URL` and the `url:` exception shows you have operated a multi-database app rather than only read about one.
- In a three-tier production block, how do you point only the Solid Queue database somewhere else without editing database.yml?Set `QUEUE_DATABASE_URL`. Rails derives the variable name from the entry name plus `_DATABASE_URL`, so it merges only into the `queue` entry, while `DATABASE_URL` keeps feeding `primary`. The YAML's `migrations_paths: db/queue_migrate` survives because the URL does not set it.
- How can you see the merged configuration a running Rails process actually uses?Ask Active Record: `ActiveRecord::Base.connection_db_config.configuration_hash` shows the hash for the current connection, and `ActiveRecord::Base.configurations.configs_for(env_name: "production")` lists every entry. Reading those in `bin/rails console` settles which host, database and pool keys won.
- When DATABASE_URL is set, Rails ignores database.yml for that environment entirely.
- YAML values win over DATABASE_URL because database.yml is loaded last.
- DATABASE_URL is merged into every entry of the environment, including cache and queue.
- A URL without a password erases the password set in database.yml.
- DATABASE_URL is still merged into an entry that already has its own url: key.
Assumes Rails 8.1; the URL merge rules are older, but the YAML key that survives the merge in these examples is max_connections, called pool: before 8.1.