This post originated from an RSS feed registered with Ruby Buzz
by Jamis Buck.
Original Post: Easy ActiveRecord Scripts
Feed Title: the buckblogs here
Feed URL: http://weblog.jamisbuck.org/blog.cgi/programming/index.rss
Feed Description: Jamis Buck's corner of the blogging universe. Mostly about ruby, but includes ramblings on a variety of topics.
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:
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.)