The maze book for programmers!
mazesforprogrammers.com

Algorithms, circle mazes, hex grids, masking, weaving, braiding, 3D and 4D grids, spheres, and more!

DRM-Free Ebook

The Buckblog

assorted ramblings by Jamis Buck

Easy ActiveRecord Scripts

3 October 2005 — 1-minute read

ActiveRecord (the ORM component of Rails) is really a pretty slick little piece of equipment. Not only does it integrate seamlessly with the other parts of the Rails stack, it can be easily used on its own. I do so frequently when trying to duplicate reported bugs. Consider the following little script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
require 'active_record'

ActiveRecord::Base.logger = Logger.new(STDERR)
ActiveRecord::Base.colorize_logging = false

ActiveRecord::Base.establish_connection(
  :adapter => "sqlite",
  :dbfile  => ":memory:"
)

ActiveRecord::Schema.define do
  create_table :foxes do |t|
    t.column :name, :string
  end

  create_table :trucks do |t|
    t.column :fox_id, :integer
    t.column :color, :string
  end
end

class Fox < ActiveRecord::Base
  has_many :trucks
end

class Truck < ActiveRecord::Base
  belongs_to :fox
end

fox = Fox.create :name => "Small"
fox.trucks.create :color => "Blue"
fox.trucks.create :color => "Orange"

puts Fox.find(1).trucks.length

The above script uses an in-memory SQLite database, so it doesn’t leave any messes around on disk. It also logs to STDERR, so I can see all the SQL that is produced, and it turns off colorized logging (because I prefer a white-background terminal and AR’s colors aren’t very friendly to that). It then defines the tables using ActiveRecord::Schema, defines the classes, adds some data, and then manipulates the data.

Nice and simple! (Note that ActiveRecord::Schema is only available in the beta gems, currently, but everything else should work with the released version of AR.)

Reader Comments

:memory: is pretty nifty, didn't know about that.
By the way, using this ActiveRecord::Base.establish_connection( :adapter => "sqlite", :dbfile => ":memory:" ) won't create a memory based sqlite database if you happen to have the full RoR environment loaded because of the following code in activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb # Allow database path relative to RAILS_ROOT. if Object.const_defined?(:RAILS_ROOT) config[:dbfile] = File.expand_path(config[:dbfile], RAILS_ROOT) end I was wondering for the longest time why I was finding a ':memory:' file in my current working directory :) Regards, Blair

Nice demo.

Don’t forget to include: require ‘rubygems’ at the top.