Easy ActiveRecord Scripts
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.)
3 Oct 2005
4 Oct 2005
Don’t forget to include: require ‘rubygems’ at the top.
21 Jun 2007