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!

Tags

.

Related Posts

April 3rd 2008 18:42 | comments (1)
 

Comments


Gravatar

PJ Cabrera

May 7th 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


(Required)

Your email address to get your Gravatar. Address itself is not shown.

(Include the http://)

(Required)

 

You Are Here


Douglas F Shearer

This is the homepage of Douglas F Shearer, a software developer and mountainbike racer. Find out more at the About page.

Gallery Latest


Side on Chips on crown Front on chip2 chip1 img67

Stay Informed


What is RSS?

Top Tags