ActiveRecord - querying polymorphic associations
Solution 1:
Argh!
I think I found the problem.
When joining via:
@comments = Comment.find(:all,
:joins => "forum_topics",
:conditions => ["forum_topics.featured = ? ", true]
)
You need the whole join!
:joins => "INNER JOIN forum_topics ON forum_topics.id = comments.commentable_id",
See the ever-awesome: http://guides.rubyonrails.org/active_record_querying.html#joining-tables
Solution 2:
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