Skip to content

Instantly share code, notes, and snippets.

@viktorchukhantsev
Forked from lexmag/article.rb_product.rb
Created April 11, 2016 10:35
Show Gist options
  • Save viktorchukhantsev/894646dcc1e8b719c0af45e99629d676 to your computer and use it in GitHub Desktop.
Save viktorchukhantsev/894646dcc1e8b719c0af45e99629d676 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment