Last active
August 18, 2024 19:08
-
-
Save seancdavis/e76e6649267655ebc461 to your computer and use it in GitHub Desktop.
Rails has_many :through Polymorphic Association (http://goo.gl/lxmehk)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/image.rb | |
class Image < ActiveRecord::Base | |
has_many :taggings, :as => :taggable | |
has_many :tags, :through => :taggings | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/post.rb | |
class Post < ActiveRecord::Base | |
has_many :taggings, :as => :taggable | |
has_many :tags, :through => :taggings | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/tagging.rb | |
class Tagging < ActiveRecord::Base | |
belongs_to :tag | |
belongs_to :taggable, :polymorphic => true | |
end |
I don't think a straightforward solution for this exists. Probably I'll need to change the database schema to account for this.
Nice work and thank you for posting. I'm curious, what's the tagging migration and schema look like?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From what I could find (specifically, this article), Rails 4 doesn't make this easy because you need to explicitly state each source type on a HMT polymorphic model.
As you've mentioned, one alternative is to query separately and combine the two arrays.
Another potential workaround is to use single table inheritance, but you'll want to make sure you have enough in common between the two models to make it a valid candidate for STI.