I have found as I’ve been working on my project that Rails has many very useful little features that may not be used all that often but are sometimes needed. As I come across them I hope to note them here in the hopes that they will help someone (myself included) at some point.

Yesterday I was reading the Agile Web Development with Rails (2nd Edition) book (hereafter AWDwR2E) and came across these useful little pieces of knowledge.

Leveraging ActiveRecord in a non-Rails application

Start by including rubygems and then include the activerecord gem:

require “rubygems”
require_gem “activerecord”

Next, establish your database connection:

ActiveRecord::Base.establish_connection(:adapter => “mysql”, :host => “localhost”, :database => “yourdatabase”)

Then, create a class that extends ActiveRecord::Base so your class will take advantage of all of the ORM plumbing that ActiveRecord provides:

class Friend < ActiveRecord::Base
end

Note that you should have a table called friends in yourdatabase for this to work. Assuming your friends table has the columns name and email, you could locate a friend named “John Doe” and update his email address with the following lines:

john_doe = Friend.find(“John Doe”)
john_doe.email = “john.doe@gmail.com”
john_doe.save

That’s all there is to it, and that’s pretty awesome!  This (ActiveRecord) is one of the really great features of Rails that makes it so easy to write a database-driven application.  Unlike most ORM frameworks, ActiveRecord (and by extension, Rails) relies on convention rather than configuration and thus you don’t have to tell it what table represents your class or what columns in the table map to what properties in your class.  It uses reflection to determine all of this although you can override it’s defaults if you need to do so.