ActiveRecord - querying polymorphic associations

前端 未结 8 1346
深忆病人
深忆病人 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 15:01

    Rails does not include a polymorphic join by default but this gem would help you to joins your polymorphic relationship with ease. https://github.com/jameshuynh/polymorphic_join

    0 讨论(0)
  • 2020-12-04 15:02

    Here is an example to adapt to your purpose.

    class AdwordsCampaign < ApplicationRecord
      has_many :daily_campaign_reports, as: :ga_campaign
    end
    
    class DailyCampaignReport < ApplicationRecord
    
      belongs_to :ga_campaign, polymorphic: true
    
      # scope
      def self.joins_ga_campaign(model)
        models = model.to_s.pluralize
        sql = <<~SQL
          INNER JOIN #{models}
          ON #{models}.id = daily_campaign_reports.ga_campaign_id
        SQL
        joins(sql).where(ga_campaign_type: model.to_s.camelize)
      end
    end
    

    Then I can use it wherever needed like this:

    DailyCampaignReport.joins_ga_campaign(:adwords_campaign)
    
    0 讨论(0)
提交回复
热议问题