This project is archived and is in readonly mode.
Custom counter caches not being used
Reported by Adam | January 2nd, 2009 @ 12:18 AM | in 3.x
If a belongs to uses a custom counter cache that is not of the form #{attribute_name}_count of the corresponding has_many association then they are not used.
A simple solution is to add a :counter_cache option to the has_many association.
The attached patch is complete with docs and tests.
Comments and changes to this ticket
-
Pratik March 7th, 2009 @ 07:15 PM
- Assigned user set to Pratik
- Tag set to activerecord, patch
- State changed from new to incomplete
I think the key needs to be named differently, probably :counter_cache_attribute or something. Also, the tests shouldn't really use mocking/stubbing.
Thanks.
-
CancelProfileIsBroken August 5th, 2009 @ 03:13 PM
- Tag changed from activerecord, patch to activerecord, bugmash, patch
-
Derander August 9th, 2009 @ 09:52 PM
To verify the fix,
rails test2
cd test2
script/generate model Post title:string custom_count:integer
script/generate model Comment title:string post_id:integer
In post.rb: has_many :comments
in comment.rb: belongs_to :post, :counter_cache => :custom_count
./script/console
p = Post.create(:title => "A Post")
p.comments.build(:title => "A comment")
p.save
p.custom_count should be 1
-
CancelProfileIsBroken August 10th, 2009 @ 02:38 AM
- Tag changed from activerecord, bugmash, patch to activerecord, patch
- State changed from incomplete to resolved
-
Derander August 10th, 2009 @ 08:47 AM
- Tag changed from activerecord, patch to activerecord, patch
Jose Valim found an error in my understanding of the patch.
The problem is not found by examining the value of p.custom_count, instead, starting from p.save:
p.custom_count = 10
p.save
p.comments.count will be 1. #It should be 10 if custom_count were being used.
-
José Valim August 10th, 2009 @ 08:51 AM
- State changed from resolved to new
Since we added :inverse_of in master (Rails 3.0), we could make use of it to retrieve the counter cache column, instead of adding a new option to has_many which may be confusing.
-
Aditya Sanghi October 24th, 2010 @ 02:40 PM
- Title changed from Add magic encoding comment to generated files to Custom counter caches not being used
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>