Ruby on rails 4 同一型号上的Rails计数器缓存?
我有一个Ruby on rails 4 同一型号上的Rails计数器缓存?,ruby-on-rails-4,counter-cache,Ruby On Rails 4,Counter Cache,我有一个模型任务,每个任务都有许多其他任务: 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 类任务
模型
任务
,每个任务都有许多其他任务:
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
类任务
我是否可以将计数器缓存添加到每个任务的子任务数?如何操作?是的,您可以添加计数器缓存
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
类任务
您需要创建一个迁移,将名为sub\u tasks\u count
的新列添加到tasks
表中。是,您可以添加计数器缓存
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
类任务
您需要创建一个迁移,将名为sub\u tasks\u count
的新列添加到tasks
表中。无需执行@Rubysmith编写的操作,您只需:
class Task < ActiveRecord::Base
belongs_to :task, counter_cache: true
has_many :tasks, dependent: :destroy
end
类任务
迁移:
class AddTaskCounterToTasks < ActiveRecord::Migration
def change
add_column :tasks, :tasks_count, :integer, default: 0, null: false
end
end
类AddTaskCountertasks
不需要做@Rubysmith写的事情,您只需:
class Task < ActiveRecord::Base
belongs_to :task, counter_cache: true
has_many :tasks, dependent: :destroy
end
类任务
迁移:
class AddTaskCounterToTasks < ActiveRecord::Migration
def change
add_column :tasks, :tasks_count, :integer, default: 0, null: false
end
end
类AddTaskCountertasks