Rails 3.2.14
Ruby 2.1.7
使用counter_cache
时,计数列将增加2,而不是1。例如:
class Finger < BaseModel
belongs_to :hand, :counter_cache => true
end
class Hand < BaseModel
has_many :fingers
end
所以,如果我这样做:
finger = Finger.new(:hand_id => 1)
finger.save
我可以在控制台中看到
(0.2ms) BEGIN
SQL (4.3ms) INSERT INTO "fingers" ("hand_id") VALUES ($1) RETURNING "id" [["hand_id", 311222]
Hand Load (0.4ms) SELECT "hands".* FROM "hands" WHERE "hands"."id" = 311222 LIMIT 1
SQL (0.7ms) UPDATE "hands" SET "fingers_count" = COALESCE("fingers_count", 0) + 1 WHERE "hands"."id" = 311222
(8.2ms) COMMIT
=> true
如您所见,COALESCE
仅被调用一次。
但是然后:
Hand[1].fingers_count
> 2
但是:
Hand[1].fingers.count
> 1
在我的应用程序中,所有这些都是通过开箱即用的导轨形式完成的,这些表单创建了与手相关的新Finger。