Skip to content

Instantly share code, notes, and snippets.

@mamantoha
Created April 5, 2018 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mamantoha/7880a2c5b155671cb8a169762f573eb8 to your computer and use it in GitHub Desktop.
Save mamantoha/7880a2c5b155671cb8a169762f573eb8 to your computer and use it in GitHub Desktop.
polymorphic_many_to_many_in_rails.md

Polymorphic many-to-many association in Rails

Migration

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

Models

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

Sample

Province.first.banners
Country.first.banners

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