Monday, July 27, 2009

ActiveRecord outside of Rails (even with ODBC)

There are three quick lines that you need in order to use ActiveRecord outside of Rails. First, you need to load gems, then you can load ActiveRecord. Then, you can pick and choose which of your models to use.

require 'rubygems'
require 'activerecord'
require @@RAILS_APP_HOME + '/app/models/foo.rb'

Then, you'll need this little snippet to establish the connection to the database for ActiveRecord:

require 'rubygems'
require 'activerecord'
require 'yaml'

@@DATABASE_CONFIGURATION = YAML::load( + '/config/databases.yml'))

def establish_connection(database)
# ActiveRecord::Base.logger =
if (dbconfig['mode'] == 'odbc')
puts("Connecting to [#{database}]: ODBC,"+
" DSN=#{dbconfig[database]['dsn']}/#{dbconfig[database]['adapter']}"+
" [user=#{dbconfig[database]['username']}]")
puts("Connecting to [#{database}]: #{dbconfig[database]['adapter']}, "+
" [user=#{dbconfig[database]['username']}]")

def remove_connection

I put the above snippet in a central ruby file, then require that file anywhere I need to use the ActiveRecord objects. After a call to establish_connection, you can start using any model you've imported. Note, you'll see a slightly different URL constructed for ODBC.


peterjohn said...

Pretty good post. I just came across your site and wanted to say that I’ve really enjoyed reading your posts. In any case I’ll be subscribing to your feed and I hope you will keep a good work!Cheer!

sap online training
software online training
sap sd online training
hadoop online training

peterjohn said...

This is one awesome blog article. Much thanks again.
I really enjoy the blog.Much thanks again. Really Great.

oracle online training
sap fico online training
dotnet online training