Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 4 同一型号上的Rails计数器缓存?_Ruby On Rails 4_Counter Cache - Fatal编程技术网

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
感谢您的洞察力!它起作用了!谢谢你的洞察力!它起作用了!