Skip to content

Instantly share code, notes, and snippets.

@lexmag
Created July 28, 2012 15:12
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save lexmag/3193707 to your computer and use it in GitHub Desktop.
Save lexmag/3193707 to your computer and use it in GitHub Desktop.
Two-way polymorphic models / Polymorphic HABTM association
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
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 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
@e-fu
Copy link

e-fu commented Jul 5, 2015

nice!

@dkobia
Copy link

dkobia commented Apr 21, 2018

brilliant indeed

@codesalley
Copy link

wow!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment