Archive for March 2nd, 2007

March 2nd, 2007

Things I wish I’d known

by Tim Cull

For my mystats Ruby on Rails project, I hand coded a SQL schema; if only I’d known then what I know now!
Rails has a cool feature called a migration, where you write basically a ruby class that describes your
database table and it does the rest for you, including versioning. So if you just want to add a column
you can create a migration to do that. If it turns out that extra column was a mistake, then you can
tell Rails to roll back just that change, no problem.

Anyhow, on my last post I was trying to learn how many-to-many relationships work in Rails. That
was a month ago, but hey, I had a birthday, my wife had a birthday, and we all had Valentine’s day,
kids got colds and ear infections here and there, so give me a break, ok? You people are such task masters.

I bought a book (Ruby on Rails Up and Running, Bruce Tate and Curt Hibbs) and read it on the bus.
Turns out it only needed about 2 pages to explain everything I needed about many-to-many. It’s that simple.

Another thing I wish I’d known, though, is that Rails (surprise, surprise) has a naming convention for
the mapping tables typically used in a many-to-many relationship. In my case, I have a table named
“people” and a table named “groups”. I’d created a mapping table called “person_groups” to map
between them, but it turns out the names have to be both plural and in alphabetical order, eg “groups_people”.
Oh, well.

Once I’ve done that, my Person and Group classes are this simple:

class Group < ActiveRecord::Base
has_and_belongs_to_many :people
end

class Person < ActiveRecord::Base
has_and_belongs_to_many :groups
end

Now I’ve got an application that allows me to create groups and view them from a home page. To get the
home page, I ventured into hand coding my own controller. I also need to have the concept of logging in and
keeping a current user in the session–I’m guessing there’s got to already be a package for that, so finding it is
my next set of homework.