Skip to content

Instantly share code, notes, and snippets.

@SteveOscar
Created December 28, 2015 18:52
Show Gist options
  • Save SteveOscar/daddf24e75dd5822f9b5 to your computer and use it in GitHub Desktop.
Save SteveOscar/daddf24e75dd5822f9b5 to your computer and use it in GitHub Desktop.
# First, the new join table, where 'taggable' establishes the polymorphic association.
class Tagging < ActiveRecord::Base #the join table
belongs_to :tag
belongs_to :taggable, :polymorphic => true #this line sets up polymorphism
end
# The tag model is associated with newspapers AND articles (polymorphism) via the join table.
class Tag < ActiveRecord::Base
has_many :newspapers, :through => :taggings, :source => :taggable,
:source_type => "Newspaper" # informs rails how to get to newspapers from tags
has_many :articles, :through => :taggings, :source => :taggable,
:source_type => "Article" # informs rails how to get to articles from tags
has_many :taggings
end
# Article and Newspaper models are connected to tags instead of to eachother.
Class Article < ActiveRecord::Base
has_many :tags, :through => :taggings #gets tags via the taggings join table
has_many :taggings, :through => :taggable # makes articles taggable
end
Class Newspaper < ActiveRecord::Base
has_many :tags, :through => :taggings # gets tags via the taggings join table
has_many :taggings, :through => :taggable # makes newspapers taggable
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment