12 Jan 2008

Using ActiveRecord outside Rails

ActiveRecord is a nice lightweight way to access database tables from Ruby code. I use it outside of Rails for simple scripts and in customer test scripts.

If you want to use ActiveRecord outside of Rails you just need to:
- Download ActiveRecord
- Configure the database
- Define the schema
That's it!

Download ActiveRecord



gem install activerecord


Configure the database


database_configuration.rb


require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:database => "appdb",
:username => "appuser",
:password => "secret"
)


Define the Schema


schema.rb


require 'database_configuration'

class Project < ActiveRecord::Base
end

class User < ActiveRecord::Base
end

class Comment < ActiveRecord::Base
end


We can now use our ActiveRecord database objects in our scripts.


script.rb


require 'schema'

user = User.find_by_username("craig@facedowndog.com")
puts user.id

comment = Comment.find_by_user_id(user.id)
puts comment.comment

projects = Project.find(:all)
puts projects.length.to_s + " projects"