ActiveRecord outside of Rails: handy DB-tool

The popular web framework Ruby on Rails has a core part called ActiveRecord. That is the ORM, the object-relational mapper, which lets you use your database records “as objects” in your code.

With Rails, ActiveRecord is very powerful, but it’s not that bad on its own either.

Here is an example of using it as a microscopic SQL utility, for the two tables “seeds” and “products”.

Sean Treadway told me how to minimize the SQLing by just defining the Seed class. ActiveRecord detects all the column names on its own, so no need to type statements anymore.

And today I found out about the handy [clone](http://api.rubyonrails.com/classes/ActiveRecord/Base.html#M000739) method. It populates the to-be-created Product with the values of the parent.


#!C:\prog\ruby\bin\ruby

# Read all the Seeds from the seeds table, and find their counterparts in the Products table
# On each match, create a new Product with the special column "parentproductid" set to the parent product's ID.
# Save a new row for each match.

require 'rubygems'
require_gem 'activerecord'

ActiveRecord::Base.establish_connection(
    :adapter  => "mysql",
    :username => "root",
    :host     => "localhost",
    :password => "secret",
    :database => "plants_db" 
)

class Product < ActiveRecord::Base
	# to be able to use the Rails reserved word "type" as a column name.
	self.inheritance_column = "lala"; 
end
class Seed < ActiveRecord::Base
	# to be able to use the Rails reserved word "type" as a column name.
	self.inheritance_column = "lala"; 
end

Product.find(:all).each do |p|
    Seed.find(:all, :conditions => [ "name = ? AND family = ?", p.name,p.family] ).each do |s|
        
	# String interpolation is done like this: "Regular talk here and #{variablename_here}."
	puts "#{p.id}: #{p.family} #{p.name} - #{s.seedprice} DKK"
  	
	# Make new product, and set its parent id column and the new price (from the Seed!)
	new_seed = p.clone
	new_seed.parentproductid = p.id
	new_seed.price = s.seedprice
	
	# Take a look at the insides of the new_seed, for fun
	st = new_seed.attributes()
	puts st.inspect
	
	# Save new Product.
	new_seed.save
       
	puts "Created seed!"
	puts 
    end
end

When I wrote this, I noted that I had not yet written the seedprice to the cloned Product. I added a line, DELETEd the products that had a non-empty parentproductid and re-ran the above script.

Using ActiveRecord can be good times. I hope your Rails appetite’s been piqued by this.

Published by Olle Jonsson

Human. Wears glasses and often a smile.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.