Rails has_many通过多态计数器缓存 [英] Rails has_many through polymorphic counter cache
本文介绍了Rails has_many通过多态计数器缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个模型,它们通过关联使用多态的has_many链接在一起,我想添加一个counter_cache,但似乎Rails/ActiveRecord不支持此功能.
I have two models I link together using a polymorphic has_many through association and I would like to add a counter_cache but it seems Rails/ActiveRecord does not support this feature out of the box.
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
推荐答案
只需为以下内容修改分类模型:
Simply modify your Classification model for the following:
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
此外,请确保分类表中具有以下列:
Also, make sure you have the following columns in your taxonomies table:
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"等)
Change "other_classifiables_count" to what you need ("answers_count", "users_count", etc.)
这篇关于Rails has_many通过多态计数器缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文