Accessing the right database

tags: [jason] [database]

Wiping my freaking Database

I spent a good hour or two getting a scrubbed copy of the production db on my machine, then I ran my freaking tests and POOF, all gone in a few seconds. What had happened was, my test and development databases were the SAME, so when dbcleaner went through, it cleaned out all my development tables. As a result I had to dig into seeing how the database was set and learned a few things.

Rails initially looks for configurations in the config/database.yml files

This is generally how Rails finds which database to use. Add an url key to point to and Bob’s your uncle. ie,

development:
  url: sqlite3:my_database

What if the database.yml is empty?

Rails simply looks for 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:

Ruby on Rails Guides: configuring a database

What if the ENV[‘DATABASE_URL’] AND a database is set in the database.yml?

The database.yml url is highest president.

$ cat config/database.yml
development:
  url: sqlite3:NOT_my_database

$ echo $DATABASE_URL
postgresql://localhost/my_database

$ bin/rails runner 'puts ActiveRecord::Base.configurations'
{"development"=>{"adapter"=>"sqlite3", "database"=>"NOT_my_database"}}

In conclusion

Make sure you have your databases set up accordingly for each environment by understanding how Rails configures the db. This is especially true if you don’t want to mistakenly alter or wipe a local scrubbed db copy, or production data.