counter_cache失效一例

counter_cache的问题
counter_cache在模型上控制计数器的变化,因此当模型发生new和delete时候触发,但对于依赖模型使用的

class Topic < ActiveRecord::Base
  has_many :posts, :dependent => :delete_all
end


由于删除topic时,生成的SQL语句如下:

DELETE FROM `topics` WHERE `id` = 13
DELETE FROM `posts` WHERE (topic_id = 13)


没有触发counter_cache,导致counter_cache计算错误。


解决的办法:

1、不使用counter_cache
2、使用
class Topic < ActiveRecord::Base
  has_many :posts, :dependent => :destroy
end


目前我使用的是后者。

你可能感兴趣的:(cache,读书,Ruby,Rails,ActiveRecord)