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
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
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)