Oct 14, 2015
Table of contents:
One of the most important and most well known features of Ruby on Rails is its Active Record ORM.
Rails’ implementation of Active Record makes accessing and working with data in your database incredibly easy. Over the years, the ORM has also picked up a lot of additional functionality to make developing web applications easier.
A big part of the “The Rails Way” of building web applications is convention over configuration. Whilst it is possible to build a Rails application without Active Record, you would be going against the grain.
In today’s tutorial we will be looking at getting started with Active Record in Ruby on Rails.
The Active Record patterns is where an object wraps a single row of the database to encapsulate database access and domain logic around that data.The Active Record pattern was first introduced in Patterns of Enterprise Application Architecture by Martin Fowler.
An Active Record object can be used to access, edit and update it’s own data. The benefit of the Active Record pattern is that it is very easy to use. You essentially just have a single class to work with for each table of your database.
The drawback is that your business logic is directly coupled with the database.
Some people love the Active Record pattern, whilst others hate it. Personally I’m a big fan of making things as simple as possible. Whilst the Active Record pattern does have downsides, I think the ease of use more than makes up for it.
There are couple of different ways to create an Active Record model in Rails using the various generator rake tasks.
But the easiest is to simply just create a new file under the models
directory:
class Article < ActiveRecord::Base
end
To create a new Active Record model you must extend from the ActiveRecord::Base
class. This means you automatically inherit all of the functionality from ActiveRecord.
In the example above, you don’t need to specify that this model should be mapped to the articles
table as Rails will automatically assume that this is the case. For the most part, as long as you stick to the Rails defaults you won’t need to do much in terms of configuration as things will “just work”.
You also don’t need to specify the columns of the table as Rails will automatically pick up column names and data types from the database schema.
Whilst you might not agree with all of these defaults and conventions, they have been chosen to make your life easier. When you follow the conventions of Rails you don’t have the overhead of choosing a style and making sure everything is consistent.
Of course you can override these conventions, but there really is no point unless you are forced to for some external reason.
Active Record objects are essentially just Ruby objects with extra abilities.
To create a new model object, you can simply call the new
method:
article = Article.new
This will create a new object, but it won’t be saved to the database just yet:
article.persisted?
# => false
To save the object to the database you can call the save
method:
article.save
article.persisted?
# => true
To create a new object and save it straight to the database you can use the create
method:
article = Article.create(title: 'Hello world')
article.persisted?
# => true
There are a couple of different methods for finding existing records from the database.
First, you can find a record by it’s id:
article = Article.find(123)
Next you can call the first
or last
methods:
first_article = Article.first
last_article = Article.last
Or you can specify WHERE
conditions:
article = Article.where(title: 'Hello world')
Or you could return all the records like this:
articles = Article.all
Once you have a model object to work with, you can update its properties in a couple of different ways.
Firstly you can just set the properties as you would with any type of Ruby object and then call the save
method:
article.title = 'All your base are belong to us'
article.save
Alternatively you can call the update
class method with a record id and pass a hash of attributes to update:
Article.update(123, title: 'All your base are belong to us')
There are two ways you can delete records from your database using Active Record.
Firstly you can call the destroy
instance method on a model object:
article.destroy
This will remove the object from the database and prevent you from manipulating the model object any longer.
Alternatively you can pass the id of the record to delete to the delete
class method:
Article.delete(123)
This will delete the object from the database directly without loading the object into a model first. This is better for performance, but might get you into trouble if you have defined before_destroy
callbacks.
A big part of the success of Rails is the “convention over configuration” mantra. By sticking to the tried and tested defaults, you can build web applications with next to no configuration or cognitive overhead of what to name things or how to match things up.
Rails’ Active Record implementation is probably the best example of the pattern. Rails has taken that original pattern from Martin Fowler’s work, and proven it can work in a huge variety of web applications.
If you are going to use Ruby on Rails, you almost have to also use Active Record. As I mentioned at the top of this article, the big benefit of using Rails is best realised by sticking to “The Rails Way”.