snax

scaling rails

sti support in has_many_polymorphs

At the request of Kevin Marsh, the polymorphs plugin now supports single-table inheritance.

example

the sti base class
class Person < ActiveRecord::Base
end
sti children
class Hipster < Person
end

class Groupie < Person
end
the collection parent class
class Concert < ActiveRecord::Base
  has_many_polymorphs :concert_goers, 
      :from => [:hipsters, :groupies]
end

Then you can do a_concert.concert_goers, a_concert.groupies, etc., and everything will work.

download

Get it here.

August 20, 2007

7 comments

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!

Evan Junkie says (September 26, 2006):

I think you are the smartest guy in the world!

Andrei Erdoss says (September 26, 2006):

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.

evan says (July 28, 2007):

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.

Andrei Erdoss says (July 28, 2007):

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?

evan says (July 28, 2007):

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.

Andrei Erdoss says (July 28, 2007):

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.

Comments are closed.