ActiveRecord - querying polymorphic associations

前端 未结 8 1362
深忆病人
深忆病人 2020-12-04 14:10

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

8条回答
  •  长情又很酷
    2020-12-04 14:44

    You Need a Conditional, Plus Rails 3+

    A lot of people alluded to it in the answers and comments but I felt that people, including myself, would get tripped up if they landed here and didn't read thoroughly enough.

    So, here's the proper answer, including the conditional that is absolutely necessary.

    @comments = Comment.joins( "INNER JOIN forum_topics ON comments.commentable_id = forum_topics.id" )
                       .where( comments:     { commentable_type: 'ForumTopic' } )
                       .where( forum_topics: { featured:         true         } )
    

    Thanks to all, especially @Jits, @Peter, and @prograils for their comments.

提交回复
热议问题