我有一个has_many :questions
用户模型和一个belongs_to :user
和belongs_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_cache
和belongs_to :user
设置belongs_to :expert, polymorphic: true
?
这样,我既可以做user.questions_count
也可以做trainer.questions_count
答案 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
这样的自定义解决方案