How to get the contents of the database.yml file from ActiveRecord

Save to delicious.

Sometimes when using Active Record you may want to create a database connection to a database other than the default database specified in your database.yml file.

When this happens, the easiest way to do it is to use the Class-level convenience method on ActiveRecord::Base. Like this:

Imagine your database.yml entry looks like this:

  adapter: mysql
  encoding: utf8
  database: foo
  pool: 5
  username: my_user
  password: my_pass
  socket: /tmp/mysql.sock

Now you want to create active record models that use that database connection. Here’s how:

# 'Bar' model points to the table 'bars' in the database 'foo'

class Bar < ActiveRecord::Base

  # specify the database.yml entry
  $db_config = 'development_foo'

  # Fetch the database.yml configuration
  $config = ActiveRecord::Base.configurations[$db_config]

 # Now we can establish a connection to that database and
 # this ActiveRecord model class will point to that database.
  establish_connection $config


It’s simple!

Copyright Kevin Bedell, 2009
All this code can be freely used under the terms of the MIT License.
This entry was posted in ruby on rails and tagged , , , , . Bookmark the permalink.
  • notsoreq


    establish_connection :development_foo

    would suffice.

    Current score: 0