ROR:计数器缓存,has_many 想法,使用嵌套参数删除

ROR: counter cache, has_many thougth, delete with nested params

我有下一个模型:

class Document < ActiveRecord::Base
  has_many :sub_roles_documents, dependent: :destroy
  has_many :sub_roles, through: :sub_roles_documents,class_name: '::SubRole'
end

class SubRole < ActiveRecord::Base
  has_many :sub_roles_documents, dependent: :destroy
  has_many :documents, through: :sub_roles_documents, class_name: '::Document'
end

class SubRolesDocument < ActiveRecord::Base
  belongs_to :sub_role, counter_cache: :documents_count, touch: true
  belongs_to :document, counter_cache: :sub_roles_count
end

并且当我删除某些使用嵌套参数的文档的 sub_roles 时,计数器缓存 sub_roles_count 不会改变,但是当我向文档添加新的 sub_roles 时,一切正常。 如果我直接删除 sub_roles 的文档 documents.sub_roles.delete(specific_sub_role) - 它也可以正常工作。 对我来说最好的方法是什么?

我想出了一个问题,都写在文档中:

This option can be used to configure a custom named :counter_cache. You only need this option when you customized the name of your :counter_cache on the belongs_to association.

就我而言,我接下来必须写:

class Document < ActiveRecord::Base
  has_many :sub_roles_documents, dependent: :destroy, counter_cache: :documents_count
  has_many :sub_roles, through: :sub_roles_documents,class_name: '::SubRole'
end

因为我使用了计数器缓存的自定义名称。