【问题标题】:Counter_cache with polymorphic and a regular belongs_to associationCounter_cache 具有多态性和常规的 belongs_to 关联
【发布时间】:2019-01-24 13:00:03
【问题描述】:

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

我需要为 User 以及 Trainer 和 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

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

这样我可以同时做到user.questions_count 和trainer.questions_count

【问题讨论】:

    标签: ruby-on-rails associations


    【解决方案1】:

    对于用户,counter_cache 可以正常工作。您可以使用以下方法实现Rails-5 的多态关联所需(使用自定义计数器缓存注明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 用于设置多态关联的 counter_cache 存在于较低版本的 Rails 中,但您可以处理提供的自定义解决方案,如 here

    【讨论】:

    • :expert_count 是什么意思? @雷
    • 对不起,我还是不明白你说的:expert_count是什么意思。我希望能够致电trainer.questions_count。 :expert_count 会这样做吗?如何? @雷
    • @jedi,当您按照提供的文档尝试 @trainer.expert_count 时,它应该按照文档工作,如果它不起作用,您可以使用自定义实现,如 stackoverflow.com/a/15725387/10522579
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多