Learn Ruby on Rails Book

Configuring and connecting to a database

There are two ways to connect to a database in a Rails application.

1. Using ENV['DATABASE_URL']

Ruby on Rails support environment variables out of the box. Sometimes, we can't commit some configurations to a repository. In such cases we use environment variables.

We can set DATABASE_URL to connect to a database. In next command, Rails will connect using postgresql adapter.

1ENV['DATABASE_URL'] # => "postgresql://localhost/granite_development?pool=5"

This method is not used in the development environment. Though this can be useful in production and heroku environment. In development, we use config/database.yml.

2. Using database.yml

We can specify all the database connection details in config/database.yml file. Using following snippet, a Rails application can connect to a postgres database.

1development:
2  adapter: postgresql
3  database: granite_development
4  pool: 5
5  username: postgres
6  password: YourPostgresPassword

Don't commit config/database.yml

We don't commit config/database.yml in a git repository. There are two reasons for this.

  1. We don't want to disclose database password information of the committer.
  2. Every developer's database details can be different i.e. username and password. Every time we push the code, there will be a conflict in a file.

If config/database.yml is missing

As mentioned config/database.yml is not pushed to the repository. So when we clone a new repository, this file will be missing.

Generally, a Rails application will have a config/database.yml.example or a config/database.yml.postgresql file.

we can copy content of this file into config/database.yml

1cp config/database.yml.postgresql config/database.yml

If no example file is present, you can copy content from the example database.yml for your application's database.

Config options

We can check selected database's connection config with ActiveRecord::Base.connection_config. We might need to configure more options. Now, let's try to understand some of the common database config options.

1host - Defaults to "localhost". This can also be a remote database URL.
2port - Port number, Defaults to 5432 for postgres.
3username - Username of the database.
4password - Password for the database.
5database - The name of the database.
6encoding - (Optional) Sets the client encoding.
7connect_timeout - The timeout to establish a new connection to the database before failing.
8read_timeout - The time to receive data after connected.
9pool - Maximum number of connections to database per application.
10  Defaults to 5.
11  e.g. 2 * 16 (puma) + 1 * 10 (sidekiq) = 42
12  here, 2 - puma processes, each process has 16 threads
13        1 - sidekiq process, each process has 10 threads

Connection Preference

In case, we use both config/database.yml and ENV['DATABASE_URL'] then configuration will be merged together. Please refer Rails guides for the merge strategy.