Fun with active_record and sqlite3

Active Record, the ORM layer in the Rails cake (and camping, and Merb, etc) is strong magic.

Before stumbling on this trick, I would create new rails projects for every little thing I needed to figure out. Running
rails test_proj -d sqlite3
is just so easy!

Yesterday, I needed to figure out a way to have a search term provide alternates (“dog” might have “puppy”, “hound”, etc.) After thinking about it for a few minutes, I decided I needed to figure out how to play with ActiveRecord without a full rails project. Here it is: ar_playground

#!/usr/bin/env ruby

%w|rubygems active_record irb|.each {|lib| require lib}

:adapter => “sqlite3″,
:database => “test.db”

ActiveRecord::Schema.define do
create_table :fruits, :force => true do |t|
t.column :name, :string

class Fruit < ActiveRecord::Base
validates_presence_of :name

Fruit.create(:name => “apple”)

IRB.start if __FILE__ == $0

This will create a sqlite3 database in the directory where it’s run, and drop you into an IRB shell with all the Classes available for playing.

If you have trouble with sqlite3, you can use mysql, or get sqlite3 running by checking out:
SQLite3 announcement on Jamis’ blog

If you’re curious what I came up with for my problem, here’s the pastie.