Nested has_many :through associations in Rails
Published 3 February 10 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
- There’s an old plugin by Matt Wescott which supported this around Rails 2.1 (I think)
- 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.
- 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
- There is something close, documented in Simulate Has Many Through HABTM by Alex Reisner.
- It worked for me.