vadus1
vadus1

Reputation: 109

how can i make a unique request for `counter_cache`

So, i have a two model Campaign and CampaignSubscription

CampaignSubscription model
I have this relation

belongs_to :campaign, inverse_of: :campaign_subscriptions, counter_cache: true, required: true

I don't get no unique number of subscriptions.

belongs_to :campaign, inverse_of: :campaign_subscriptions, required: true

counter_culture :campaign, column_name: proc { |model|
self.where(lead_id: model.lead_id, campaign_id: model.campaign_id).count > 1 ? nil : 'campaign_subscriptions_count' }

But I think it's wrong and will cause N+1.

Now when the user creates the next CampaignSubscription object, I’m not receiving a unique number of subscriptions. I need to make the number of subscriptions unique to the user (Lead). How to more cleanly organize the code?

Upvotes: 0

Views: 141

Answers (1)

bo-oz
bo-oz

Reputation: 2872

I would define this as a method on the campaign subscription class, instead of trying some kind of counter cache. I would only use a counter cache on the parent model to describe counts in a simple one-to-many (maybe with a filter publishedL:true), but not for counting related records in the same table. Use a model method for that:

def some_describing_method_name
  campaign.campaign_subscriptions.pluck(:lead_id).uniq.count
end

Upvotes: 1

Related Questions