ActiveRecord

I took a bit of a dive today and looked a Ruby on Rails presentation. Here’s what I gleaned from looking through all the slides.

  • Rails is a web application framework that allows your Ruby to interact with the web seamlessly. By “interact with the web”, I assume the presentation means “interact with databases.”

  • Rails implements a principle called “MVC” — Model View Controller. Rails seems to handle each task separately. I’m going to focus on the Model, which uses ActiveRecord.

  • ActiveRecord is a Module that Rails uses to model and interact with databases. It makes database queries both simple and intuitive.

Here are some concrete query comparisons between using SQLite3 versus Rails’ ActiveRecord.

Assume we have a table called “dogs,” each with a name, age, weight, and type. Each attribute would be a column, and each row would represent a different dog.

Table using SQLite3
1
2
3
4
5
6
7
CREATE TABLE dogs (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  name TEXT;
  age INTEGER;
  weight INTEGER;
  type TEXT
);

We can also imagine this as a class of Dog objects in Ruby. Here’s how one might create the barebones structure in Ruby.

Dogs as objects of class Dog in Ruby
1
2
3
class Dog
  attr_accessor :id, :name, :age, :weight, :type
end
Table initialized using Rails’ ActiveRecord
1
2
class Dog < ActiveRecord::Base
end

See how simple that was? Now we can make queries on the table.

SQLite3 query for first dog in table
1
SELECT * FROM dogs WHERE id=1;
Rails query for first dog in table
1
Dog.find(1)

That’s just the beginning! Check this out.

SQLite3 query appending conditions
1
SELECT * FROM dogs WHERE age=8 AND type="corgi";
Rails query appending same conditions
1
Dog.find_by_age_and_type 25, "corgi"

It seems like ActiveRecord must use certain keywords like ‘by’ and ‘and’ in order to dynamically use the attribute names that the user inputs.

What is really beautiful though is the idea of “configuration of convention” that Rails implements in order to shorten the amount of code you need to write. Slides 42-44 of the presentation gave a particularly good example of the idea. No wonder people love Rails!

The slides continue talking about the MVC

Comments