Counter_cache с полиморфной и регулярной ассоциацией принадлежат - PullRequest
0 голосов
/ 24 января 2019

У меня есть модель User, которая has_many :questions и вопрос, оба belongs_to :user и belongs_to :expert, as polymorphic: true. Эксперт может быть тренером или врачом

Мне нужен кеш счетчика для User, а также для Тренера и Доктора.

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

Можно ли настроить counter_cache для belongs_to :user и belongs_to :expert, polymorphic: true?

Таким образом, я мог бы сделать и user.questions_count, и trainer.questions_count

1 Ответ

0 голосов
/ 24 января 2019

Для пользователя counter_cache может работать нормально. Вы можете добиться требуемой полиморфной ассоциации для Rails-5, используя ниже (используя пользовательский счетчик кеша, отмеченный здесь ),

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

Проблема для установки counter_cache для полиморфной ассоциации присутствует для более низкой версии рельсов, но вы можете иметь дело с пользовательским решением, предоставленным как здесь

...