Rails counter_cache for Model.count 没有任何关联,为了让SELECT COUNT(*)更快 [英] Rails counter_cache for Model.count without any association, in order to make SELECT COUNT (*) faster
问题描述
我正在使用 Model.count
对我的一个模型中的行进行总计,并且有点担心性能,因为最终这个模型会变得非常大,因此 SELECT COUNT (*)
很慢.
I'm totaling the rows in one of my models using Model.count
and am a bit concerned about performance, as eventually, this model will get very large, and, therefore, SELECT COUNT (*)
very slow.
有没有办法在没有 :belongs_to
关系的情况下使用 counter_cache
?或者另一种性能友好的计算行数的方法?我想制作另一个模型,只是一个我像这样存储计算的模型,但不确定这是最好的方法.
Is there a way to use counter_cache
without the :belongs_to
relationship? Or another performance-friendly way of counting the rows? I thought about making another model, just one where I store calculations like this but not sure that's the best way.
推荐答案
比创建 Cache
模型更简单的方法是使用 Rails.cache
.
Even more trivial than making a Cache
model is to just use Rails.cache
.
Rails.cache.read("elephant_count") #=> nil
Rails.cache.write("elephant_count", 1) #=> true
Rails.cache.read("elephant_count") #=> 1
Rails 默认使用文件存储(tmp/cache).
Rails uses a file store by default (tmp/cache).
然后您可以将 Rails.cache.write 增量和减量放入模型的 after_create
和 after_destroy
挂钩中,并覆盖 Model.size
调用 Rails.cache.read.
Then you could just place a Rails.cache.write increment and decrement into your model's after_create
and after_destroy
hooks, and override Model.size
with a call to Rails.cache.read.
您可以在 Rails 首次初始化时初始化缓存,方法是在 config/initializers 中放置一个类似于 initialize_cache.rb
的文件,其中包含:
You could initialize the cache whenever Rails first initializes by placing a file named something like initialize_cache.rb
in config/initializers containing:
Rails.cache.write('elephant_count', 0) if Rails.cache.read('elephant_count').nil?
这篇关于Rails counter_cache for Model.count 没有任何关联,为了让SELECT COUNT(*)更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!