Bad code, bad humour and bad hair.

Recursive Many-to-many Association in Rails

Mar 17th, 2009

I’m fairly new to Ruby on Rails and I needed a way to create a recursive many-to-many association, but search as I may, the best help I could find was always on RailsRocket, and frankly their article, along with a lot of rails tutorials I’ve been reading, all leave a lot to be desired.

So here goes, a Recursive many-to-many association in Rails tutorial by a Rails newbie.

I’m using Ruby 1.8.7, RubyGems 1.2.0, Rails 2.1.0 and Linux.

App. Description

For this example I’m going to go with the what the RailsRocket article went over breifly. That is a Student database where we are mapping Tutors.

Why is this recursive? Well a Tutor is a Student, a Tutor teaches a Student and a Student is Tutored by a Student. Get it?

Getting started

Initialise the app:

12

$ rails students
$ cd students

Create Student Scaffold

12

$ rake db:migrate
$ script/generate scaffold Student name:string

Enter some students

Starting up the server and navigating to the students url should produce an empty listing.

1

$ script/server

Now just put in some students so that we have something to play with. I created two: ‘Dave’ and ‘Frank’.

Add Rails associations

The only way I’ve been able to get this to work the way I want is to add an intermediate association on Student to it’s Tutorships and then the actual association we want to use to map right through, via they has_many :through functionality.

For those who can make more sense of code, add the following associations to app/model/student.rb: