sti support in has_many_polymorphs
At the request of Kevin Marsh, the polymorphs plugin now supports single-table inheritance .
example
class Person < ActiveRecord::Base
endclass Hipster < Person
end
class Groupie < Person
endclass Concert < ActiveRecord::Base
has_many_polymorphs :concert_goers,
:from => [:hipsters, :groupies]
endThen you can do a_concert.concert_goers, a_concert.groupies, etc., and everything will work.
download
Get it here.
August 20, 2007
7 comments
How would you setup the scenario where Concert was also a STI table with RockConcert and JazzConcert as children?
class RockConcert < Concert end class JazzConcert < Concert end
So as the end result you can get
a_groupie.rock_concerts or a_hipster.jazz_concerts.
That would probably require an acts_as_double_polymorphic_join between both class sets.
But really, if you’re using that much STI in your system, you’re probably doing it wrong.
Well I thought about using the acts_as_double_polymorphic_join, but Concert is only STI and the type would always be the same in the join table, meaning ‘Concert’.
Is there an easy way of getting the result without using the double polymorphic join?
You can use the regular has_many_polymorphs on the base class, but you’d have to write your own accessors for each child class. A select {|o| o.is_a? self.class } might do fine, but you’ll need to watch your DB to make sure you aren’t reloading data that is actually already available in the base association.
Thank you for the quick replies. It’s not as straighforward as I thought. At the same time the thing I’m trying to accomplish is not very common. Great job with the plugin.


Kevin Marsh says (September 26, 2006):
You made my day! Thanks very much, I’m going to try it out tonight and give you a full report.
Thanks again!