Hide database queries in Rails console


Most of the time I think it’s useful to see what database queries your commands are generating in the Rails console. The rest of the time the output gets in the way by spamming your console output. It is really easy to turn this logging on and off from inside the console, just run the following command when you want to silence the output:

ActiveRecord::Base.logger.level = 1

This will set the logger’s level to INFO. Then to turn it back on enter:

ActiveRecord::Base.logger.level = 0

This will set the logger’s level back to DEBUG.

Advertisements

Keeping database passwords for Rails apps out of version control


I started using Capistrano to deploy Rails apps recently and came upon the conundrum of database passwords in version control.

In the past I have deployed Rails apps by hand and have kept database usernames and passwords out of my version control only entering them manually in the final stage of deployment. It is a very bad idea to put database credentials in your version controlled files. This process thwarts the key advantages of using Capistrano, you can’t let Capistrano handle creating your tables if it’s unaware of how to access the database and it’s not really an option to tell Capistrano “wait for a minute here for me to change a couple things then you can continue”.

This leaves us with two options; store the database.yml file outside of the rails root and get Capistrano to symlink it in place or enable Ruby to pull the credentials to be pulled into the database.yml file.

Option 1

Place this code in your config/deploy.rb file and copy the database.yml file you are going to use to shared/config/database.yml.

after "deploy:update_code","deploy:dbyml_symlink"

namespace :deploy do
  task :dbyml_symlink do
    rm #{release_path}/config/database.yml && 
    ln -nfs #{deploy_to}/#{shared_dir}/config/database.yml #{release_path}/config/database.yml
  end
end
Option 2

For this method your database.yml file needs to be checked into version control. Secondly you need to put the database password somewhere safe on your server I suggest somewhere like /home/deploy_user/.myapp_db, chown it to the user running your Rails app and chmod it 400. Finally database.yml such that the production section looks something like this:

production:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: myapp_production
  pool: 5
  username: myapp_db_user
  password: <%= begin IO.read("/home/deploy/.myapp_db") rescue "" end %>
  socket: /var/lib/mysql/mysql.sock

You can be more paranoid and include the username, database name, socket, whatever in this method.

Conclusion

I prefer the second as it works out of the box, i.e. a clean clone of the repository then bundle install && bundle exec rake db:migrate && bundle exec rails s will result in a working application.