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)
.....