Thibaud Clement
Thibaud Clement

Reputation: 6897

Rails 4: setup Postgresql with environment variables in development after migration from sqlite3

In my Rails 4 app, I used to use the default Sqlite3 in development and test, while using Postgresql in production (Heroku).

I just switched from Sqlite3 to Postgresql for all three environments and everything works fine.

My current database.yml looks like that:

default: &default
  adapter: postgresql
  encoding: unicode
  username: XXX
  password: <--- empty --->
  database: name-of-my-app
  pool: 5

development:
  <<: *default
  host: localhost

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  host: localhost

production:
  <<: *default
  host: localhost

As you can see, I am using the default username (my Mac OSX username) and password (no password) and they are hard coded in the database.yml file.

If I understand correctly from what I have read here and there, this is a double bad practice, and I should instead:

  1. define custom username and passwords

  2. do so with environment variables

Is that correct, and what would be the right approach to doing it?

Upvotes: 1

Views: 916

Answers (1)

Matt Brictson
Matt Brictson

Reputation: 11092

Using your Mac OS X username and no password for development and test is fine. This is how PostgreSQL is set up by default by homebrew, and it is a common configuration for Mac Rails developers.

If you deploy to Heroku, then Heroku will already specify a DATABASE_URL environment variable for you; there is nothing you need to do.

The changes I suggest to your setup are:

  1. You probably don't need to specify a username. If you installed PostgreSQL with homebrew, then your username is the default pg user anyway, so it is redundant.
  2. Specify a different test database. Using the same database name for both dev and test will cause problems.
  3. Completely delete the production section of database.yml. Heroku injects the necessary environment variable, so you don't need it.

With these changes, your database.yml should look like this:

development:
  adapter: postgresql
  encoding: unicode
  database: name_of_my_app_development
  min_messages: WARNING
  pool: 5

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: postgresql
  encoding: unicode
  database: name_of_my_app_test
  min_messages: WARNING
  pool: 5

Upvotes: 1

Related Questions