Douglas F Shearer

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:

  1. 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.
  2. Wait for Rails 2.1.0 to be released, if you’re patient!

Enjoy!

 

Comments


Gravatar

PJ Cabrera

May 07 2008 00:03

Hi Dougal,

Ooh, nice new digs! I didn't know you had redesigned the site. I still had your old feed URL in my reader and came by to get your need feed URL. :-)

Thanks for the rails write-ups, you help me stay up-to-date, mate! :-p

I hope your knee is doing better!

Add Your Comments


Commenting is closed for this entry.

 

You Are Here


Douglas F Shearer

This is the homepage of Douglas F Shearer, a software developer and mountainbike racer. More…

Hire Me!


I'm available for hire. Ruby, Java and PHP work, both remotely (Worldwide) and locally (Scotland). Find out more or email me.

Flickr Latest


Stay Informed


What is RSS?

Categories


  1. Bike (93)
  2. Coding (85)
  3. Other (46)

Top Tags