给出以下模型和架构:
create_table "posts", force: :cascade do |t|
t.integer "comments_count", default: 0, null: false
end
create_table "comments", force: :cascade do |t|
t.integer "post_id"
end
class Post
has_many :comments
end
class Comment
belongs_to :post, counter_cache: true
end
运行以下代码段会产生一些奇怪的行为:
post = Post.create
post.comments_count # 0
post.comments.count # 0
comment = Comment.create
5.times do
comment.reload
comment.post = post # NOTE: not saved but executes UDPATE for counter cache
end
post.reload
post.comments_count # 5
post.comments.count # 0
任何修复方法,以便只在实际修改外键时修改计数器缓存(最好是在事务中)?
日志:
Comment Load (0.4ms) SELECT "comments".* FROM "comments" WHERE "comments"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
Post Load (0.2ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" DESC LIMIT $1 [["LIMIT", 1]]
SQL (6.2ms) UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) + 1 WHERE "posts"."id" = $1 [["id", 1]]