[Rails] Re: Polymorphic, many-to-many, self-referential data model

Jason King
Sat, 20 May 2006 23:09:41 -0000

Josh, you wrote,
>Jason King wrote:
>> No matter what I try I''ve been unable to work how to get this
to work with
>> the cool ActiveRecord helpers.  I''m not sure if it''s
possible, Josh Susser''s
>> blog suggests it is, but damned if I can work it out...
>
>Interesting combination of polymorpic and self-ref with through. I think
>this should do it...

Wasn''t quite right, apart from the :source => :article and :source
=> :book
in the container, there were some other small things which brought things to
a halt.  Basically in the "to elements" stuff in the Container the
lack of
the foreign key in the "has_many :ownerships" (which I''ve
renamed) meant that
the JOIN was wrong.

I ended up coding things like this (with some slight name changes to make
more sense, and some work on the "to elements" stuff in Container).
I''m
still not sure if this is the best way to do it, but it seems to work, and
*does* actually make sense to me :)

  class Container < ActiveRecord::Base
    # to owner
    has_many :ownerships, :as => :element
    has_many :owners, :through => :ownerships

    # to elements
    has_many :ownings, :class_name => "Ownership", :foreign_key
=> "owner_id"
    has_many :containers,
             :through => :ownings,
             :conditions => "ownerships.element_type =
''Container''"
    has_many :chunks,
             :through => :ownings,
             :conditions => "ownerships.element_type =
''Chunk''"
  end

Chunk, you can probably guess from the above (just a name change from your
":ownings" to my ":ownerships" which made more sense to me.
The all
important (thank you, thank you, thank you) Ownership class remained the
same.

You truly are a legend, I knew this was complex, and throught that it might
have been outside the realm of these helpers.  Thanks for taking the time to
code up some very helpful code.

--
Every man is free to rise as far as he''s able or willing, but the
degree to
which he thinks determines the degree to which he''ll rise. -- Ayn Rand