[Req] polymorphic associations howto


#1

Hi people,

I’m looking into polymorphic associations as a way to cleanup some
messy parts of my code. I think they will allow me to do exectly what
I need, but since there’s little to none written on this subject, I’d be
delighted if someone could shed some light on this. Especially what
the different options and needed table structures need to be.

Thanks,

  • Fabien

#2

On 10 Feb 2006, at 10:35, Fabien F. wrote:

Hi people,

I’m looking into polymorphic associations as a way to cleanup some
messy parts of my code. I think they will allow me to do exectly what
I need, but since there’s little to none written on this subject,
I’d be
delighted if someone could shed some light on this. Especially what
the different options and needed table structures need to be.

Chad F. has a rails recipe in the works talking about polymorphic
associations. It should be in one of the next beta versions of the
book. I can highly recommend it, it goes there where the Agile book
stops.

Best regards

Peter De Berdt


#3

On 2/10/06, Peter De Berdt removed_email_address@domain.invalid wrote:

the different options and needed table structures need to be.

Chad F. has a rails recipe in the works talking about polymorphic
associations. It should be in one of the next beta versions of the
book. I can highly recommend it, it goes there where the Agile book
stops.

Best regards

Peter De Berdt

Polymorphic joins are kind of like an inverted STI setup. Before, I’d
have to use STI to join a single Asset model to multiple models
(Articles, Books, Albums, for example).

class Asset < ActiveRecord::Base
end

class ArticleAsset < ActiveRecord::Base
belongs_to :article, :foreign_key => ‘object_id’
end

class Article < ActiveRecord::Base
has_many :assets, :class_name => ‘ArticleAsset’
end

Using polymorphic joins gets rid of the redundant *Asset models:

class Asset < ActiveRecord::Base

describes a generic ‘attachable’ class

uses attachable_id as foreign key, and attachable_type

belongs_to :attachable, :polymorphic => true
end

class Article < ActiveRecord::Base
has_many :assets, :as => :attachable
end

Don’t let this stop you from getting the Rails Recipe book. I can’t
recommend it enough. And, I’m quite sure Chad’s explanation will be
much better :wink:


Rick O.
http://techno-weenie.net


#4

class Article < ActiveRecord::Base
has_many :assets, :class_name => ‘ArticleAsset’
end

Thanks Rick,

This is exactly the kind of info I’m looking for. I also used STI to
solve
this kind of thing before; it’s the ‘mess’ I was talking about :wink:

Looking forward to see it revealed further in the beta book!

  • Fabien