ruby-on-rails - Rails has_many 通过多态计数器缓存

标签 ruby-on-rails activerecord polymorphism has-many-through counter-cache

我有两个模型,我通过关联使用多态 has_many 链接在一起,我想添加一个 counter_cache,但似乎 Rails/ActiveRecord 不支持此功能。

class Classifiable < ActiveRecord::Base
  has_many :classifications, :as => :classifiable, :foreign_key => :classifiable_id
end

class Taxonomy < ActiveRecord::Base
  has_many :classifications, :as => :taxonomy, :foreign_key => :taxonomy_id
end

class Question < Classifiable
  has_many :categories, :through => :classifications, :as => :classifiable, :source => :taxonomy, :source_type => "Category"
end

class Category < Taxonomy
  has_many :questions, :through => :classifications, :source => :classifiable, :source_type => "Question"
end

class Classification < ActiveRecord::Base
  attr_accessible :classifiable, :classifiable_id, :classifiable_type,
                  :taxonomy, :taxonomy_id, :taxonomy_type

  belongs_to :classifiable, :polymorphic => true
  belongs_to :taxonomy,     :polymorphic => true
end

最佳答案

只需针对以下内容修改您的分类模型:

class Classification < ActiveRecord::Base
  attr_accessible :classifiable, :classifiable_id, :classifiable_type,
                  :taxonomy, :taxonomy_id, :taxonomy_type

  belongs_to :classifiable, :polymorphic => true
  belongs_to :taxonomy,     :polymorphic => true

  before_create  :increment_counter
  before_destroy :decrement_counter

  private

  # increments the right classifiable counter for the right taxonomy
  def increment_counter
    self.taxonomy_type.constantize.increment_counter("#{self.classifiable_type.downcase.pluralize}_count", self.taxonomy_id)
  end

  # decrements the right classifiable counter for the right taxonomy
  def decrement_counter
    self.taxonomy_type.constantize.decrement_counter("#{self.classifiable_type.downcase.pluralize}_count", self.taxonomy_id)
  end
end

另外,请确保您的分类表中有以下列:
t.integer :questions_count,           :null => false, :default => 0
t.integer :other_classifiables_count, :null => false, :default => 0
t.integer :other_classifiables_count, :null => false, :default => 0
t.integer :other_classifiables_count, :null => false, :default => 0

将“other_classifiables_count”更改为您需要的(“answers_count”、“users_count”等)

关于ruby-on-rails - Rails has_many 通过多态计数器缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15725386/

相关文章:

c++ - 具有类型转换的多态复制构造函数

java - 如何用其他内容替换此 "if"语句?

c++ - C++ 17中的泛型工厂机制

ruby-on-rails - Rails created_at 查找条件

html - 使用rails中的link_to在 anchor 标记上指定附加属性

ruby-on-rails - 缓存资源耗尽 Imagemagick

ruby-on-rails - Rails 3 : Model. 全部 => NoMethodError:未定义方法 'accept' 为 nil:NilClass

ruby-on-rails - 覆盖 Sublime Text 中的片段

ruby-on-rails - 交易中的 Rails 交易?

php - yii2 以其他名称将 ActiveRecord 属性作为 JSON 返回