This project is archived and is in readonly mode.
Counter cache not used for size and count through has_many associations
Reported by Alexandre da Silva | February 18th, 2009 @ 06:24 PM | in 2.x
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)
.....
Comments and changes to this ticket
-
Alexandre da Silva April 5th, 2009 @ 02:23 AM
- Tag set to activecord, association, counters, counter_cache
With final release of 2.3 this seems to be working. thank's
-
CancelProfileIsBroken August 6th, 2009 @ 12:58 PM
- State changed from new to resolved
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>