There are two ways to connect to a database in a Rails application.
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
1ENV['DATABASE_URL'] # => "postgresql://localhost/granite_development?pool=5"
This method is not used in the development environment. Though this can be
heroku environment. In development, we use
We can specify all the database connection details in
file. Using following snippet, a Rails application can connect to a postgres
1development: 2 adapter: postgresql 3 database: granite_development 4 pool: 5 5 username: postgres 6 password: YourPostgresPassword
We don't commit
config/database.yml in a git repository. There are two reasons
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
we can copy content of this file into
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.
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
In case, we use both
config/database.yml and ENV['DATABASE_URL'] then
configuration will be merged together. Please refer
for the merge strategy.