Changing Database Setting in Rails 2.0

As Rails 2.0 uses SQLite as the default database, you need to use rails -d mysql name_of_your_app to use MySQL as your database. I, however, forget this, and find myself deleting the app and run the command line once again.

So, I compared an app generated with SQLite with one with MySQL. Here is a visual result of diff thanks to Changes. Click the image to enlarge.

diff_mysql_salite_thumnail.jpg

Three files are different.

  • a line containing a hash for protect_from_forgery in application.rb. We don’t have to care this.
  • line containing session_key and it’s secret in environment.rb. We don’t have to care this.
  • the database.yml is completely differnt. We need complete rewriting.

What this means is that in order to change the setting, all you need to do is simply rewrite the database.yml. So, I decided to write a TextMate snippet that contains the entire content of the setting.

Here’s a snippet


# MySQL.  Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
#   gem install mysql
# On Mac OS X:
#   sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql
# On Mac OS X Leopard:
#   sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
#       This sets the ARCHFLAGS environment variable to your native architecture
# On Windows:
#   gem install mysql
#       Choose the win32 build.
#       Install MySQL and put its /bin directory on your path.
#
# And be sure to use new-style password hashing:
#   http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
  adapter: mysql
  encoding: utf8
  database: ${1:app_name}_development
  username: ${2:root}
  password: $3
  socket: /tmp/mysql.sock

# 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: mysql
  encoding: utf8
  database: ${1:app_name}_test
  username: ${2:root}
  password: $3
  socket: /tmp/mysql.sock

production:
  adapter: mysql
  encoding: utf8
  database: ${1:app_name}_production
  username: ${2:root}
  password: $3
  socket: /tmp/mysql.sock

I assign tab trigger to “database” and scope selector to “source.yaml”. The way to use is simple. Open database.yml and delete the content. Then, type database and ⇥(tab) and voila! (Note: I don’t recommend you use the same username and password for all of the environments.)