Issues with Has_Many :Through, Cache, Touch and Counter_Cache

counter_cache not decrementing for has_many associations in ActiveReord

Same issues here but on Rails 2.3.
Worth noticing that also adding a touch, like:

belongs_to :user, :counter_cache => :saved_shows_count, :touch => true

Won't update counter cache nor the related updated_at field on association.delete(object).

To workaround the issue usually we manipulate the join model, but that also have some drawbacks.

Patch is here: https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/2824-patch-has_many-through-doesnt-update-counter_cache-on-join-model-correctly#ticket-2824-18

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

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.

Is it possible to track something else with a counter_cache other than the number of objects in an association?

You can't use counter cache directly, but you can use the underlying increment function. See the documentation. To do what you say, you'd want:

Post.increment_counter(:view_count, post.id)

This issues a single SQL update command.



Related Topics



Leave a reply



Submit