0

I have next models:

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

And when I delete sub_roles for some documents using nested parameters counter cache sub_roles_count doesn't change, but when I add new sub_roles to documents all work fine. If I directly remove sub_roles of documents documents.sub_roles.delete(specific_sub_role) - it's work fine too. What is best way in my case?

kunashir
  • 917
  • 8
  • 21

1 Answers1

0

I figured out a problem, all wrote in documentation:

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.

In my case I must write next:

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

Because I use the customize name for counter cache.

kunashir
  • 917
  • 8
  • 21