drumaddict
7/28/2012 - 3:12 PM

Two-way polymorphic models / Polymorphic HABTM association

Two-way polymorphic models / Polymorphic HABTM association

class Video < ActiveRecord::Base # Image class is similar
  has_many :medium, as: :representable
  with_options through: :medium, source: :ownable do |assn|
    assn.has_many :articles, source_type: 'Article'
    assn.has_many :products, source_type: 'Product'
  end

  # If you want to get users
  # with_options source: :user do |assn|
  #   assn.has_many :articles_users, through: :articles
  #   assn.has_many :products_users, through: :products
  # end

  # def users
  #   articles_users + products_users
  # end
  # and so on...
end
class Medium < ActiveRecord::Base
  with_options polymorphic: true do |assn|
    assn.belongs_to :representable
    assn.belongs_to :ownable
  end
end

# def change
#   create_table :media do |t|
#     t.references :representable, polymorphic: true #, index: true in Rails 4
#     t.references :ownable, polymorphic: true #, index: true in Rails 4

#     t.timestamps
#   end

#   add_index :media, [:representable_id, :representable_type]
#   add_index :media, [:ownable_id, :ownable_type]
# end
class Article < ActiveRecord::Base # Product class is similar
  belongs_to :user
  has_many :media, as: :ownable
  with_options through: :media, source: :representable do |assn|
    assn.has_many :videos, source_type: 'Video'
    assn.has_many :images, source_type: 'Image'
  end
end