Rails: Fix has_many through polymorphic has_many Relationships
Ok, so the title is a bit of a mouthful, but stick with this, the answer to a longstanding Ruby on Rails problem is at hand.
The Setup
Imagine you have a setup similar to the following:
class User < ActiveRecord::Base
has_many :albums, :as => :albumable
end
class Album < ActiveRecord::Base
belongs_to :albumable, :polymorphic => true
has_many :images
end
class Image < ActiveRecord::Base
belongs_to :album
end
So a User has many albums, which have many images. But, albums have a polymorphic relationship, so they can belong to other objects if required.
The Problem
The problem comes when we want to fetch all the images that belong to our user.
Thinking about it, we should just add has_many :images, :through => :albums
to the user model, but unfortunately this breaks in Rails 2.0.2 and prior versions.
The Solution
Easy, just do one of the following:
- Upgrade to Edge Rails, which may carry risks depending on your app setup, but does fix this issue along with adding lots of shiny new features.
- Wait for Rails 2.1.0 to be released, if you’re patient!
Enjoy!