Understanding ActiveRecord: A Gentle Introduction to the Heart of Rails (Part 2)by Gregory Brown
It's now time to get back to building The World's Best Social Bookmarking half-app while learning about ActiveRecord, the Rails Object-Relational Mapper, along the way. If you have not read the first part of this article, you'll want to do that before continuing on here. It explains some core ActiveRecord concepts as well as some of the details about the app we're trying to build.
We still have a lot of ground to cover. The last time around, we got our
Entry model up and running, but it was still a little simplistic. Besides, we are going to need a
User model before we can officially be part of the WebTwoOh craze. That means we will need to understand how Rails handles relationships between models.
The concept of the associations between tables in a database can get pretty deep if you let it. I took an entire course at my university dedicated to the relational algebra that describes it. Though that stuff is interesting, it's not really the level we want to be thinking at.
Instead, let's think in terms of our application: A user is going to have many entries, and those entries are going to have tags.
The code to describe this is going to be crazy easy, I promise. Still, for the visually minded, this diagram shows the bird's eye view of what we're trying to model.
Hooking Up Our User Model
Relationships usually aren't much fun if they involve just one entity. Since the only thing we've got built so far is our
Entry model, we still have to write code to introduce users and tags. For no particular reason, we'll start with the
We're going to explore a few core ActiveRecord and Rails concepts along the way, so hopefully you won't mind taking the scenic route. If not, feel free to skim out the code you need and fly on through the next couple sections, meeting back up with us in the "Adding Entries to Users" section.
For those of you you decided to stay, let's generate our
$ script/generate model user
As with the
Entry model, this will dump a whole bunch of files we'll eventually need to get around to touching. Let's start with the table definition (
A simple description of a
User would be a model with a username, a display name, and an email address. We'll worry about hooking up entries in a bit, but we need to model those traits first. This is pretty much the same dance we did when creating the
Entry model earlier.
Our migration will look like this:
class CreateUsers < ActiveRecord::Migration def self.up create_table :users do |t| t.column :username, :string t.column :display_name, :string t.column :email, :string end end def self.down drop_table :users end end
For each new migration, we need to update our database to reflect the change:
$ rake db:migrate