Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
a polymorphic many-to-many association in Rails

This was my solution for a polymorphic many-to-many association

class ItemCountry < ActiveRecord::Base
  belongs_to :locatable, :polymorphic => true
  belongs_to :country
  # fields are :locatable_id, :locatable_type, :country_id
end

class Title < ActiveRecord::Base
  has_many :countries, :through => :item_countries, :as => :locatable
  has_many :item_countries, :as => :locatable
end

 class Country < ActiveRecord::Base
   has_many :titles, :through => :item_countries, :source => :locatable, :source_type => 'Title'
   has_many :item_countries, :foreign_key => :country_id
 end

 class CreateItemCountryAssociationTable < ActiveRecord::Migration
   def change
     create_table :item_countries, :id => false do |t|
       t.integer :locatable_id
       t.string  :locatable_type
       t.integer :country_id
     end
     add_index :item_countries, [:locatable_id, :locatable_type, :country_id], :name => 'polymorphic_many_to_many_idx'
     add_index :item_countries, [:locatable_id, :locatable_type], :name => 'polymorphic_locatable_idx'
   end
 end

Now I can do Title.new.countries or Country.new.titles (but not Country.new.items. Country needs to know which polymorphic / locatable item you want. I've only told it about Titles)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.