Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Counter cache not used for size and count through has_many associations

#2009

counter_cache feature is not working correctly with rails version 2.2.2 and 2.3.0 RC1

The counter is incrementing and decrementing as well, but the size and count methods, over association are issuing a SQL COUNT to the database on every call.

to reproduce create a new rails application (2.2.2 or 2.3RC1) define the migrations ans models as folows:


create_table :projects do |t|
  t.string :name
  t.integer :tasks_count
  t.timestamps
end

create_table :tasks do |t|
  t.references :project
  t.string :name
  t.timestamps
end

class Project < ActiveRecord::Base
  has_many :tasks
end

class Task < ActiveRecord::Base
  belongs_to :project, :counter_cache => true
end

Open up a console and see the log:


p = Project.create :name => 'My Project'
>>   Project Create (0.5ms)   INSERT INTO "projects" ("name", "tasks_count", "created_at", "updated_at") VALUES('My Project', NULL, '2009-02-18 18:02:28', '2009-02-18 18:02:28')
p.tasks.create :name => 'Task 1'
>> Task Create (0.7ms)   INSERT INTO "tasks" ("name", "created_at", "project_id", "updated_at") VALUES('Task 1', '2009-02-18 18:03:45', 1, '2009-02-18 18:03:45')
>>  Project Load (0.8ms)   SELECT * FROM "projects" WHERE ("projects"."id" = 1) 
>>  Project Update (0.4ms)   UPDATE "projects" SET "tasks_count" = COALESCE("tasks_count", 0) + 1 WHERE ("id" = 1) 
p.tasks.create :name => 'Task 2'
>> Task Create (0.7ms)   ... UPDATE "projects" SET "tasks_count"...
p.tasks.create :name => 'Task 3'
>>  Task Create (0.7ms)  ... UPDATE "projects" SET "tasks_count"...
p.tasks.size
>> SQL (0.6ms)   SELECT count(*) AS count_all FROM "tasks" WHERE ("tasks".project_id = 1)
p.tasks.count
>> SQL (0.6ms)   SELECT count(*) AS count_all FROM "tasks" WHERE ("tasks".project_id = 1)
.....

Reported by Alexandre da Silva · February 18th, 2009 @ 06:24 PM

State: resolved
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. Alexandre da Silva
    Alexandre da Silva
    • Tag set to activecord, association, counters, counter_cache

    With final release of 2.3 this seems to be working. thank's

    April 5th, 2009 @ 02:23 AM

  2. CancelProfileIsBroken
    CancelProfileIsBroken
    • State changed from new to resolved

    August 6th, 2009 @ 12:58 PM