Skip to content

Instantly share code, notes, and snippets.

@bf4
Last active February 6, 2024 21:13
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save bf4/4742122 to your computer and use it in GitHub Desktop.
Save bf4/4742122 to your computer and use it in GitHub Desktop.
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)

@khanhtripla
Copy link

Thanks, It would be more clearly if has more than 1 locatable_type

@bf4
Copy link
Author

bf4 commented Oct 22, 2020

no problem. Funny to see you found this gist of mine from 2013

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