1

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

jedi
  • 2,003
  • 5
  • 28
  • 66

1 Answers1

2

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

ray
  • 5,454
  • 1
  • 18
  • 40
  • What do you mean by `:expert_count`? @ray – jedi Jan 24 '19 at 13:57
  • Sorry, I still don't understand what you mean by `:expert_count`. I want to be able to call `trainer.questions_count`. Is `:expert_count` going to do this? How? @ray – jedi Jan 24 '19 at 14:08
  • @jedi, it should work as per documentation when you try `@trainer.expert_count` as per doc provided, if it do not work you can work out with custom implementation like https://stackoverflow.com/a/15725387/10522579 – ray Jan 25 '19 at 05:11