Using ActiveRecord without Rails

Here's a quick example of using Ruby ActiveRecord outside of Rails. In this case I'm saving a new record to an employees table in a MySQL database.

require "rubygems"
require_gem "activerecord"

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

class Employee < ActiveRecord::Base
end

employee = Employee.new
employee.first_name = "Fred"
employee.last_name = "Flinstone"
employee.save

In this case I'm connecting to a local MySQL database with a username of "root" and no password (admittedly not at all secure).

I already had Rails installed, so getting this code to work was just a matter of writing this script, but if you don't have ActiveRecord installed, you can install it like this:

gem install activerecord

A lot of times I write Ruby code that has nothing to do with web pages and Rails, and it's nice to be able to use ActiveRecord without all the other Rails goo.