ruby-on-rails-3performancehas-many-throughhas-manycounter-cache

Counter cache doesn't get updated - not sure why


I have a stores application on github. I'm trying to implement counter_cache for two models, 1. Divisions model and 2. Products model. For some reason I'm not sure of the counter cache(divisions_count) doesn't get incremented automatically for the Company model whenever I create a new Division and similarly the products_count doesn't get incremented for the Divisions model when I add a new product to the division.

I'm on rails 3.2.11 and on ruby 1.9.3-p327

My application is only at POC level.

PFB the model structure wrt Company, Division and Product:-

company.rb

class Company < ActiveRecord::Base
  attr_accessible :contact_no, :email_id, :fax_no, :name, :website, :divisions_count
  has_many :divisions #just added divisions_count to attr_accessible not sure if it helps
  has_many :products, :through => :divisions
end

division.rb

class Division < ActiveRecord::Base
  attr_accessible :company_id, :name, :products_count
#just added products_count to attr_accessible not sure if it helps
  belongs_to :companies, :counter_cache => true
  has_many :products
end

product.rb

class Product < ActiveRecord::Base
  attr_accessible :division_id, :model, :name, :price
  belongs_to :divisions, :counter_cache => true
end

In case you want to refer to the migrations that I've created for the counter cache implementation , you may find them here.


Solution

  • I believe the problem is that you’ve set up belongs_to incorrectly by using the plural name. Switching to singular solves the problem, i.e.

    # pseudo diff:
    
    -  belongs_to :companies, :counter_cache => true
    +  belongs_to :company, :counter_cache => true
    
    -  belongs_to :divisions, :counter_cache => true
    +  belongs_to :division, :counter_cache => true
    

    When editing models/associations I found it helpful to think of an actual instance. So, it makes sense that the “Windows”-division belongs to “Microsoft”-company, but it makes no sense that it belongs to “Microsoft”-companies. Or just remember belongs_to is always singular and has_many is always plural.

    If you need your divisions to belong to multiple companies, you need to use a different association called “has and belongs to many” or HABTM for short (see [1]).

    [1] http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association