Topic: Can I use has_many with polymorphic childrens?

I am developing a website with diverse content, each content type is a separate model using a separate database.
However, each type of content belongs to a specific catalog. Catalogues can be nested:

class Catalog < ActiveRecord::Base
  has_many :children, :dependent => :destroy, :source => :images # but different types of content use different DB tables :(
  belongs_to :parent, :class_name => 'Catalog', :foreign_key => "parent_id"
  # table fields:  parent_id:int,  name:string, description:text ...
end

# content types:
class Image < ActiveRecord::Base
  belongs_to :parent, :class_name => 'Catalog', :foreign_key => "parent_id"
  # table fields:  parent_id:int,  name:string, filepath:string, ...
end

class Product < ActiveRecord::Base
  belongs_to :parent, :class_name => 'Catalog', :foreign_key => "parent_id"
  # table fields:  parent_id:int,  name:string, cost:float, ...
end

# other content types ....

Maybe my model design is wrong, but I don`t know right solution

Last edited by somewater (2012-04-04 07:11:07)

Re: Can I use has_many with polymorphic childrens?

Now I`m find this solution:

create_table :section_joins do |t|
  t.integer :section_id
  t.integer :content_id
  t.string :content_type
end

class SectionJoin < ActiveRecord::Base
  belongs_to :section
  belongs_to :content, :polymorphic => true
end

class Section < ActiveRecord::Base

  belongs_to :parent, :foreign_key => :parent_id, :class_name => 'Section'
  has_many :children, :foreign_key => :parent_id, :class_name => 'Section', :dependent => :destroy

  has_many :section_joins, :dependent => :destroy
end

# and many types of content:

class Content < ActiveRecord::Base
  has_one :section_join, :as => :content
end