Counter cache doesn't use cache when classname can't be pluralized #7993

uladar opened this Issue Oct 19, 2012 · 4 comments


None yet
6 participants

uladar commented Oct 19, 2012

class Classroom < ActiveRecord::Base
  has_many :classroomship, :dependent => :destroy

class Classroomship < ActiveRecord::Base
  set_table_name 'classrooms_parentum'
  belongs_to :classroom, :counter_cache => :classrooms_parentum_count

class AddClassroomsParentumCountToClassroom < ActiveRecord::Migration
  def self.up
    add_column :classrooms, :classrooms_parentum_count, :integer, :default => 0

classroom = Classroom.last
 ->  (0.5ms)  SELECT COUNT(*) FROM `classrooms_parentum` WHERE `classrooms_parentum`.`classroom_id` = 109
 => 6 

But when I add new classroomship classrooms_parentum_count will be updated

classroom.classroomship.create(:parentis => Parentis.first)
-> SQL (0.2ms)  UPDATE `classrooms` SET `classrooms_parentum_count` = COALESCE(`classrooms_parentum_count`, 0) + 1 WHERE `classrooms`.`id` = 109

Rails 3.1.3


al2o3cr commented Oct 19, 2012

This doesn't look like a pluralization issue exactly - the problem is that the code to look up counter cache column to use makes an incorrect assumption about what the name of the column should be:

It uses #{}_count (classroomship_count in this example) instead of the value configured on the belongs_to.

At a minimum, we should probably add an option to has_many to select which counter cache column to use.


steveklabnik commented Oct 19, 2012

Okay, so that means it appears present on master as well.

@vladislav-rvd , 3.1 isn't supported any longer, you should upgrade as soon as you can.


senny commented Nov 4, 2012

I attached a PR, which introduces the :counter_cache option to has_many as @al2o3cr described.


matthewrobertson commented Dec 7, 2012

@jonleighton @senny I'm leaning into a few counter_cache bugs right now and this commit seems like it might be counter productive. See issues: #7630 #3903. I will try to write up a more thorough explanation when I have it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment