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.

7 Comments

  1. Kevin Marsh
    Posted August 20, 2007 at 8:28 PM | Permalink

    You made my day! Thanks very much, I’m going to try it out tonight and give you a full report.

    Thanks again!

  2. Evan Junkie
    Posted August 20, 2007 at 8:28 PM | Permalink

    I think you are the smartest guy in the world!

  3. Andrei Erdoss
    Posted August 20, 2007 at 8:28 PM | Permalink

    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.

  4. evan
    Posted August 20, 2007 at 8:29 PM | Permalink

    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.

  5. Andrei Erdoss
    Posted August 20, 2007 at 8:30 PM | Permalink

    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?

  6. evan
    Posted August 20, 2007 at 8:31 PM | Permalink

    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.

  7. Andrei Erdoss
    Posted August 20, 2007 at 8:32 PM | Permalink

    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.

Follow

Get every new post delivered to your Inbox.

Join 66 other followers