Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple counter_cache in Rails model

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

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

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.

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

like image 243
Tomasz Cudziło Avatar asked Jul 17 '10 11:07

Tomasz Cudziło


1 Answers

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

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

Note: not actually tested.

like image 187
Taryn East Avatar answered Oct 13 '22 17:10

Taryn East