Using Active Record in the Console

I’m going to be using mainly the console. The console is really useful for accessing your app without having to use a web front end. Lots of people think that it is only available in Rails, but its actually available with any Ruby installation using IRB (Interactive Ruby). All you need to do is pass the -r option, followed by the ruby file you want to load:

irb -r main.rb

This will then give you access to all the methods in the main.rb file as well as being able to interact with the database if one is defined in main.rb.

To demonstrate this I’m going to create a database of Manchester United football team players. First of all I need to install the latest version of Active Record. This is a pre-release and has some dependencies that also need instaling. Entering the following code in the console does the trick:

sudo gem install tzinfo,memcache-client,arel,activerecord --pre

Now I need some code that will set the database up and fill it with some data. Here is the code in full:

I’m going to put the name and position of each player into the database as well as the country they play for and how many goals they have scored for Manchester United.

After this there are lots of lines creating each player.

At the end is a Sinatra handler that I’ll discuss at the end. In fact you don’t actually need Sinatra to interact with the database at all, the following lines at the beginning are only needed if you plan to make this into a web app:

require 'rubygems'
require 'sinatra'

Let’s see what Active Record is made of:

Player.all

This will produce an array of all the players, which is a bit too long, so instead, let’s test out the count method:

This means I can easily find out the average goals scored by all of the non-English players:

Player.foreign.average(:goals).to_i
=> 32

And there you have it - a nice way to play around with your database. I was quite impressed with the new way of performing method chaining in Active Record, although it seemed a lot like what DataMapper already does. You can read more about the new methods over at Pratik’s blog.

Finally I decided to just show that this is easy to turn into a web app with a simple handler at the end. This is a little bit of Ruby that finds all the players and puts them into a list.