Thursday, March 6, 2008

has_many_polymorphs

This is a good plugin, with some not so good docs on the Rails wiki for a total newbie. But i have a some good links which i will put with this post.

The basic use of HMP is to model the relationship of a particular entity with a bunch of other entities which are not of the same type. Say you want to Model the relation of a Person having many Houses, Cars and Offices. The number of associations and join tables that you'd have to create is scary. Writing has_many and belongs_to statements in your models are not half as much a hassle as creating and using join tables for all these relations. And what if you wanted them all together to display something like Person has such n such Properties where Properties are the Houses, Cars, Offices?

Bit of quick sand you got yourself into, what? ;)


HMP helps with this. You write a single has_many_polymorphs statement in your model for the owning entity, create a table to represent ownerships and you're set...

The rails wiki has some explanation :
http://wiki.rubyonrails.org/rails/pages/HowToUsePolymorphicAssociations

But a good explanation lies here:
http://m.onkey.org/2007/8/14/excuse-me-wtf-is-polymorphs

But in all the million polymorph articles i read, the instructions were to put require 'has_many_polymorphs' before the initializer block in the environment.rb.

When i did this i got a very upsetting error nil.warn error when i tried to access any page within my site.
The fix is: Please put require 'has_many_polymorphs' AFTER the initializer block in the environment.rb. . It will save you a lot of pain, suffering and mental torture.


You could use the ruby console to familiarize yourself with the relationships.. fire it up with ruby/script console ...


0 comments: