Yossale February 2016

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?

Answers


Rubysmith February 2016

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.

Post Status

Asked in February 2016
Viewed 2,522 times
Voted 4
Answered 1 times

Search




Leave an answer