Sunday, March 08, 2009

How to test out ActiveRecord in irb

I like how interpreted languages provide this interpreter for you to try out stuff. As I am learning ruby on rails I frequently need to try out ActiveRecord's dark ways of doing things and I would like to be able to try it out in irb so here is what I do
Launch irb
irb --simple-prompt

and then execute the following code assuming you are in the rails app directory



require 'rubygems'

require 'active_record'

require 'yaml'

Dir.glob(File.join(File.dirname(__FILE__), './app/models/*.rb')).each {|f| require f }

dbconfig =
YAML::load(File.open('./config/database.yml'))

currenv =
ENV["RAILS_ENV"]

if not currenv

currenv =
"development"

end

currdbconfig = dbconfig[currenv]

currdbconfig[
"database"] = currdbconfig["database"]

#p currdbconfig

ActiveRecord::Base.establish_connection(currdbconfig)




After thins you can try out your model methods in the prompt.

This works with MySQL and should work with sqllite3 without any problems

2 comments :

stormtrooper57 said...

Excellent! just what I needed.

Unknown said...

Or you could change to your rails app folder and run rails console. No need to load config files, etc. manually.