Rails 模型中的多个 counter_cache [英] Multiple counter_cache in Rails model

查看:32
本文介绍了Rails 模型中的多个 counter_cache的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Rails,但遇到了一个小问题.我正在编写带有任务列表的死简单应用程序,因此模型看起来像这样:

I'm learning Rails, and got into a little problem. I'm writing dead simple app with lists of tasks, so models look something like that:

class List < ActiveRecord::Base
  has_many :tasks
  has_many :undone_tasks, :class_name => 'Task',
                          :foreign_key => 'task_id',
                          :conditions => 'done = false'
  # ... some validations
end

List 模型的表包含 tasks_counterundone_tasks_counter 列.

Table for List model has columns tasks_counter and undone_tasks_counter.

class Task < ActiveRecord::Base
  belongs_to :list, :counter_cache => true
  # .. some validations
end

对于这样的代码,List 实例有 attr_readonly :tasks_counter ,但我也想有一个计数器来处理未完成的任务.有没有办法让 Rails 自动缓存多个计数器.

With such code there is attr_readonly :tasks_counter for List instances but I would like to have a counter for undone tasks as well. Is there any way of having multiple counter cached automagically by Rails.

到目前为止,我已经设法创建了增加或减少 Task#undone_tasks_counterTasksObserver,但也许有更简单的方法.

So far, I've managed to create TasksObserver that increments or decrements Task#undone_tasks_counter, but maybe there is a simpler way.

推荐答案

您是否尝试过使用自定义计数器缓存列?这里的文档:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

Have you tried it with a custom-counter-cache column? The doc here: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

它建议您可以将列名传递给 counter_cache 选项,您可能可以调用两次,例如

It suggests that you can pass a column-name to the counter_cache option, which you may well be able to call twice eg

belongs_to :list, :counter_cache => true     # will setup tasks_count
belongs_to :list, :counter_cache => :undone_tasks_count

注意:未经实际测试.

这篇关于Rails 模型中的多个 counter_cache的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆