Ruby On Rails : Configuring a Database using Database.yml && ENV

Configuring a Database:

You can connect to the database by setting an environment variable ENV['DATABASE_URL'] or by using a configuration file called config/database.yml.

development:
  adapter: postgresql
  database: blog_development
  pool: 5

OR

> puts ENV['DATABASE_URL']
postgresql://localhost/blog_development?pool=5

The config/database.yml file contains sections for three different environments in which Rails can run by default:

Important:

  • The config/database.yml file can contain ERB tags <%= %>. Anything in the tags will be evaluated as Ruby code. You can use this to pull out data from an environment variable or to perform calculations to generate the needed connection information.Since it is possible to embed ERB in your config/database.yml it is best practice to explicitly show you are using the ENV['DATABASE_URL'] to connect to your database. This is especially useful in production since you should not commit secrets like your database password into your source control (such as Git).
    $ cat config/database.yml
    production:
      url: <%= ENV['DATABASE_URL'] %>
  • If you have an empty config/database.yml file but your ENV['DATABASE_URL'] is present, then Rails will connect to the database via your environment variable.

Sources:

http://guides.rubyonrails.org/configuring.html#connection-preference

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s