ActiveRecord - querying polymorphic associations

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

    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
    

提交回复
热议问题