I am using polymorphic associations to track Comments in my project. All very straight forward stuff.
The problem I have is in querying based on the polymorphic asso
An old question, but there is a cleaner way of achieving this by setting up a direct association for the specific type along with the polymorphic:
#comment.rb
class Comment < ActiveRecord::Base
belongs_to :commentable, polymorphic: true
belongs_to :forum_topics, -> { where( comments: { commentable_type: 'ForumTopic' } ).includes( :comments ) }, foreign_key: 'commentable_id'
...
end
You are then able to pass :forum_topics to includes getting rid of the need for a messy join:
@comments = Comment
.includes( :forum_topics )
.where( :forum_topics => { featured: true } )
You could then further clean this up by moving the query into a scope:
#comment.rb
class Comment < ActiveRecord::Base
...
scope :featured_topics, -> {
includes( :forum_topics )
.where( :forum_topics => { featured: true } )
}
...
end
Leaving you to be able to simply do
@comments = Comment.featured_topics