Polymorphic many-to-many association in Rails
class CreateBannerCategories < ActiveRecord ::Migration
def change
create_table :banner_categories do |t |
t . integer :banner_id
t . integer :category_id
t . string :category_type
t . timestamps
end
end
end
class BannerCategory < ActiveRecord ::Base
belongs_to :category , polymorphic : true
belongs_to :banner
# fields are :category_id, :category_type, :banner_id
end
class Banner < ActiveRecord ::Base
has_many :provinces , through : :banner_categories , source : :category , source_type : "Province"
has_many :countries , through : :banner_categories , source : :category , source_type : "Country"
has_many :banner_categories , foreign_key : :banner_id
end
class Country < ActiveRecord ::Base
has_many :banners , through : :banner_categories , as : :category
has_many :banner_categories , as : :category
end
class Province < ActiveRecord ::Base
has_many :banners , through : :banner_categories , as : :category
has_many :banner_categories , as : :category
end
Province . first . banners
Country . first . banners
Banner . first . provinces
Country . first . provinces