jedi
jedi

Reputation: 2198

Counter_cache with polymorphic and a regular belongs_to association

I have a User model that has_many :questions and a Question both belongs_to :user and belongs_to :expert, as polymorphic: true. An expert can be a Trainer or a Doctor

I need a counter cache for both User and the Trainer and Doctor.

class Question < ApplicationRecord
  belongs_to :user
  belongs_to :expert, polymorphic: true

  has_many :answers, dependent: :destroy
end

class User
  has_many :questions
  has_many :answers, as: :responder
end

class Trainer
  has_many :questions, as: :expert
end

class Doctor
  has_many :questions, as: :expert
end

Is it possible to set up counter_cache for both belongs_to :user and belongs_to :expert, polymorphic: true?

This way I could do both user.questions_count and trainer.questions_count

Upvotes: 1

Views: 573

Answers (1)

ray
ray

Reputation: 5552

For user, counter_cache can work normally. You can achieve required for polymorphic association for Rails-5 using below (using custom counter cache noted here),

class Question < ApplicationRecord
  belongs_to :user, counter_cache: true
  belongs_to :expert, polymorphic: true, count_cache: :expert_count
end

class Trainer
  has_many :questions, as: :expert
end

class Doctor
  has_many :questions, as: :expert
end

Issue for setting counter_cache for polymorphic association is present for lower version of rails but you can deal with custom solution provided like here

Upvotes: 2

Related Questions