0

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?

LHH
  • 3,233
  • 1
  • 20
  • 27
Yossale
  • 14,165
  • 22
  • 82
  • 109

2 Answers2

2

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.

Rubysmith
  • 1,165
  • 8
  • 12
0

There's no need for doing what @Rubysmith wrote, you can just:

class Task < ActiveRecord::Base
  belongs_to :task, counter_cache: true
  has_many :tasks, dependent: :destroy
end

Migration:

class AddTaskCounterToTasks < ActiveRecord::Migration
  def change
    add_column :tasks, :tasks_count, :integer, default: 0, null: false
  end
end
Miguel Peniche
  • 981
  • 10
  • 20