Counter_cache具有多态性和常规的Emirates_to关联

时间:2019-01-24 13:00:04

标签: ruby-on-rails associations

我有一个has_many :questions用户模型和一个belongs_to :userbelongs_to :expert, as polymorphic: true问题。专家可以是培训师或医生

User和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

是否可以同时为counter_cachebelongs_to :user设置belongs_to :expert, polymorphic: true

这样,我既可以做user.questions_count也可以做trainer.questions_count

1 个答案:

答案 0 :(得分:1)

对于用户而言,counter_cache可以正常工作。您可以使用以下方法(使用标记为here的自定义计数器缓存)来实现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

Issue用于为低版本的rails设置用于多态关联的counter_cache,但是您可以处理here

这样的自定义解决方案