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

Jason King
Sat, 20 May 2006 10:49:06 -0000

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...

I have:

Container which can contain one or more Element.  An Element is a polymorph
of either a Container or a Chunk.  An Element can exist in one or more
Containers.  I use a table called ownerships as the join between Containers
and Element.  Here''s some code:

  create_table :containers do |t|
    t.column :name, :string
  end

  create_table :chunks do |t|
    t.column :name, :string
  end

  create_table :ownerships do |t|
    t.column :name, :string
    t.column :container_id, :integer
    t.column :element_id, :integer
    t.column :element_type, :string
  end

Then in the models:

  class Chunk < ActiveRecord::Base
    has_many :ownerships, :as => :element
  end

  class Ownership < ActiveRecord::Base
    belongs_to :element, :polymorphic => true
    # belongs_to :container
  end

  class Container < ActiveRecord::Base
    has_many :ownerships, :as => :element
    # has_many :ownerships
  end

Ok, so far so good.  The above works as expected.  What is commented out is
my attempt at coding the important relationship between the Container and the
Ownership, not as a Element but as the parent (ie. referenced by
container_id).  I''ve tried a number of options, including all sort of
attempts with :through and various other things.

I understand why it doesn''t work, obviously the relationship defined
already
for Container''s access to ownerships gets in the way, or takes
precedence or
whatever.  It doesn''t matter what I''ve tried, the result sets
are always
giving me the "Element" relationship of Container to Ownership, not
the
direct parental relationship.

Any clues?

--
We can evade reality, but we cannot evade the consequences of evading reality.
        -- Ayn Rand