Skip to content

Instantly share code, notes, and snippets.

@levicole
Forked from seancdavis/image.rb
Created May 17, 2017 19:34
Show Gist options
  • Save levicole/613ee0c32227970f25293bca77f3a8d4 to your computer and use it in GitHub Desktop.
Save levicole/613ee0c32227970f25293bca77f3a8d4 to your computer and use it in GitHub Desktop.
Rails has_many :through Polymorphic Association (http://goo.gl/lxmehk)
# app/models/image.rb
class Image < ActiveRecord::Base
has_many :taggings, :as => :taggable
has_many :tags, :through => :taggings
end
# app/models/post.rb
class Post < ActiveRecord::Base
has_many :taggings, :as => :taggable
has_many :tags, :through => :taggings
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/tagging.rb
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :taggable, :polymorphic => true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment