ruby-on-rails-4counter-cache

Rails Counter Cache On the same model?


I have a model Task, and each task has_many other tasks:

Class Task < ActiveRecord::Base
  belongs_to :sub_task, class_name: Task.name, touch: true
  has_many :sub_tasks, class_name: Task.name, foreign_key: :sub_task_id, dependent: :destroy
end

Can I add a counter cache to the number of sub_tasks each task has? How?


Solution

  • Yes you can add the counter cache.

    class Task < ActiveRecord::Base
       belongs_to :sub_task, class_name: Task.name, touch: true, counter_cache: :sub_tasks_count
       has_many :sub_tasks, class_name: Task.name, foreign_key: :sub_task_id, dependent: :destroy
    end
    

    You need to create a migration to add a new column named sub_tasks_count to the Tasks table.