seancdavis
10/13/2014 - 7:53 PM

Rails has_many :through Polymorphic Association (http://goo.gl/lxmehk)

Rails has_many :through Polymorphic Association (http://goo.gl/lxmehk)

# app/models/tagging.rb

class Tagging < ActiveRecord::Base
  belongs_to :tag
  belongs_to :taggable, :polymorphic => true
end
# app/models/tag.rb

class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :posts, :through => :taggings, :source => :taggable,
    :source_type => 'Post'
  has_many :images, :through => :taggings, :source => :taggable,
    :source_type => 'Image'
end
# app/models/post.rb

class Post < ActiveRecord::Base
  has_many :taggings, :as => :taggable
  has_many :tags, :through => :taggings
end
# app/models/image.rb

class Image < ActiveRecord::Base
  has_many :taggings, :as => :taggable
  has_many :tags, :through => :taggings
end