问题描述
我不熟悉计数器缓存的概念,而且我的应用主页之一的加载时间过长,我相信我需要继续下去.
I am new to the concept of counter caching and with some astronomical load times on one of my app's main pages, I believe I need to get going on it.
我需要实现的大多数计数器缓存都附加了某些(简单的)条件.例如,这是一个常见的查询:
Most of the counter caches I need to implement have certain (simple) conditions attached. For example, here is a common query:
@projects = employee.projects.where("complete = ?", true).count
当我显示一个列出公司所有员工的项目计数的表单时,我遇到了上述 N+1
查询问题.
I am stumbling into the N+1
query problem with the above when I display a form that lists the project counts for every employee the company has.
我真的不知道我在做什么所以请纠正我!
I don't really know what I'm doing so please correct me!
# new migration
add_column :employees, :projects_count, :integer, :default => 0, :null => false
# employee.rb
has_many :projects
# project.rb
belongs_to :employee, :counter_cache => true
迁移之后……这就是我需要做的全部吗?
After migrating... is that all I need to do?
我如何才能在我提到的条件下工作以最大限度地减少加载时间?
How can I work in the conditions I mentioned so as to minimize load times?
推荐答案
关于 counter_cache
的条件,我会读这个 博文.
With regards to the conditions with counter_cache
, I would read this blog post.
您应该做的一件事是将以下内容添加到迁移文件中:
The one thing you should do is add the following to the migration file:
add_column :employees, :projects_count, :integer, :default => 0, :null => false
Employee.reset_column_information
Employee.all.each do |e|
Employee.update_counters e.id, :projects_count => e.projects.length
end
因此,您当前的项目计数可以迁移到与每个 Employee 对象关联的新 projects_count
.在那之后,你应该很高兴.
So you current projects count can get migrated to the new projects_count
that are associated with each Employee object. After that, you should be good to go.
这篇关于具有条件的列的计数器缓存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!