1

所以,我有一个 Folder 和一个 FolderItem 模型。

更新

# == Schema Information
#
# Table name: folders
#
#  id                 :integer         not null, primary key
#  name               :string(255)     not null
#  parent_folder_id   :integer
#  user_id            :integer         not null
#  folder_itens_count :integer         default(0)
#  created_at         :datetime
#  updated_at         :datetime
#

class Folder < ActiveRecord::Base
...

  belongs_to :parent_folder, :class_name => 'Folder'
  has_many :child_folders, :class_name => 'Folder', :foreign_key => :parent_folder_id
  has_many :folder_itens, :order => 'created_at DESC'

  after_update {
    update_parent_folder_itens_count
  }

  def update_parent_folder_itens_count
    parent_folder = self.parent_folder
    if self.folder_itens_count_changed? && parent_folder
      quant_changed = self.folder_itens_count - self.folder_itens_count_was
      parent_folder.increment(:folder_itens_count, quant_changed)
    end
  end
end

class FolderItem < ActiveRecord::Base
... 
  belongs_to :folder, :counter_cache => :folder_itens_count
end

我正在使用 counter_cache 来保留单个文件夹的数量。但是一个文件夹可能是另一个文件夹的父文件夹,我希望父文件夹具有所有子文件夹的 counter_cache 总和加上它自己的 counter_cache。

为此,我尝试将 after_update 方法缓存在 counter_cache 列中所做的更改,但不知何故,在创建新的 FolderItem 时不会调用此方法。

4

1 回答 1

1

我会做这样的事情。

将一些缓存计数器字段添加到文件夹表

$ rails g migration add_cache_counters_to_folders child_folders_count:integer \
                                                  folder_items_count:integer  \
                                                  total_items_count:integer   \
                                                  sum_of_children_count:integer

和 Ruby 代码

class Folder < ActiveRecord::Base
  belongs_to :parent_folder, class_name: 'Folder', counter_cache: :child_folders_count
  has_many :child_folders, class_name: 'Folder', foreign_key: :parent_folder_id
  has_many :folder_items

  before_save :cache_counters

  # Direct descendants - files and items within this folder
  def total_items
    child_folders_count + folder_items_count
  end

  # All descendants - files and items within all the folders in this folder
  def sum_of_children
    folder_items_count + child_folders.map(&:sum_of_children).inject(:+)
  end

private
  def cache_counters
    self.total_items_count = total_items
    self.sum_of_children_count = sum_of_children
  end
end

class FolderItem < ActiveRecord::Base
  belongs_to :folder, counter_cache: true # folder_items_count
end

请注意Folder#sum_of_children- 方法是递归的,因此对于大型数据集,它可能会减慢您的应用程序。您可能想对它做更多的 SQL 魔术,但作为纯 Ruby,这与我能得到的一个很好的解决方案一样接近。我看到您以相反的方式进行操作,这与您需要从下至上更新一样慢。(这是自上而下)

不知道这是否是您要查找的内容,但它是一种用于缓存文件夹中项目数量的可读解决方案。

于 2012-02-23T01:06:51.110 回答