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
How to Export a Rails Model to JSON Schema
Rails Routing: Giving Default Values for Path Helpers
Why Do I Need Asterisk Before an Array
Rails - Link_To Helper with Data-* Attribute
Best Way to Use HTML5 Data Attributes with Rails Content_Tag Helper
How to Implement Composite Primary Keys in Rails
Normal Variables VS Instance Variable in Ruby, Whats the Difference
Best Way to Remove File Extension
Where Do You Put CSS Files in a Rails App Directory
Breaking a Large Rails App into Smaller Apps
Ruby - Problems with Expect and Pty
User Selected CSS Stylesheet in Rails
What Purpose Can Anonymous Modules Serve
Generating Sequential Numbers in Multi-User Saas Application
Emacs Ruby Method Parameter Indentation