Wednesday, October 15, 2008

Multiple Database Connections using ActiveRecord

Define your extra database connections In the database.yml config file:

development:
adapter: sqlite3
database: db/development.sqlite3
timeout: 5000

db1:
adapter: sqlite3
database: db/db1.sqlite3
timeout: 5000

db2:
adapter: sqlite3
database: db/db2.sqlite3
timeout: 5000

Now create a dbx.rb file in your models directory and define a class for each database connection:

class Db1 < ActiveRecord::Base
self.abstract_class = true
establish_connection "db1"
end

class Db2 < ActiveRecord::Base
self.abstract_class = true
establish_connection "db2"
end

Add the following to your environment.rb file:

include "dbx"

You will now be able to use "Db1" and "Db2" in your app to connect to 2 other databases.

Open up an existing model class in your project:

class User < ActiveRecord::Base
has_many :messages, :dependent => :destroy
end

Now replace "ActiveRecord::Base" with "Db1"

class User < Db1
has_many :messages, :dependent => :destroy
end

The User class is now set to retrieve data from the "db1" database.

Tuesday, October 14, 2008

method(object) vs object.method

A time formatting function that accepts a time object and returns a string containing a formatted time:

def military(time)
time.strftime("%Y-%m-%d %H:%M:%S")
end

def usa(time)
time.strftime("%Y-%m-%d %I:%M:%S %p")
end

military(Time.now)
usa(Time.now)

Sometimes extending a class to include a desired behavior will produce cleaner, more readable code:

class Time

def military
self.strftime("%Y-%m-%d %H:%M:%S")
end

def usa
self.strftime("%Y-%m-%d %h:%M:%S %p")
end

end

Time.now.military
Time.now.usa

The "non-Ruby way" of doing things: Requesting a set of records from a database table the old fashion way

Whenever possible, try to avoid using the following method to request a set of records. You'll be better off if you did it the Ruby way.

def query(str)
ActiveRecord::Base::connection.select_all(str)
end

If you do choose to go this route, remember to properly sanitize your query strings.