Latest Notebook Article

Nested has_many :through associations in Rails

Published 6 days ago by Justin French

It can’t be done. You’re surprised, so am I. I spent a few hours looking tonight, Rails (2.3.5 at the time of writing) doesn’t do this. Even the rdoc says it:

You can only use a :through query through a belongs_to or has_many association on the join model.

I have no idea about Rails 3 with the Arel changes to ActiveRecord, but here’s everything else I picked up along the way:

The Bad News

  1. There’s an old plugin by Matt Wescott which supported this around Rails 2.1 (I think)
  2. There’s a newer plugin by Ian White on GitHub based off Matt’s, which worked with Rails 2.1–2.2 it seems, but was busted by Rails 2.3. There’s a branch for Rails 2.3, which it looks like they’re still working on (last commit December 2009). I didn’t try it.
  3. There’s an open ticket in Rails’ Lighthouse, everyone +1s the idea, no one has written a patch, Pratik marked it as incomplete, awaiting a patch from the community. You should try to make that patch!

The Good News

  1. There is something close, documented in Simulate Has Many Through HABTM by Alex Reisner.
  2. It worked for me.

In Short

What is this?

portrait of Justin

This is the online home of Justin French, a designer & web application developer located in Melbourne, Australia. I’m working with CLEAR Interactive – the best Ruby on Rails and iPhone team in Melbourne.

» read more

Search