ActiveRecord - querying polymorphic associations

前端 未结 8 1350
深忆病人
深忆病人 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:51

    Checked to work under Rails 5:

    Solution 1:

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

    or

    Solution 2:

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

    Pay attention to the raw SQL syntax: no backticks are allowed. See http://guides.rubyonrails.org/active_record_querying.html#joining-tables .

    I personally prefer Solution 1 as it contains fewer raw SQL syntax.

提交回复
热议问题