使用:counter_cache和:触摸相同的关联

Mat*_*nde 9 caching ruby-on-rails

我有一个Comment模型,belongs_to一个Message.在comments.rb我有以下几点:

class Comment < ActiveRecord::Base
  belongs_to :message, :counter_cache => true, :touch => true
end
Run Code Online (Sandbox Code Playgroud)

我已经这样做了,因为更新counter_cache不会更新updated_at时间Message,我希望更新cache_key.

但是,当我查看我的日志时,我注意到这会导致两个单独的SQL更新

Message Load (4.3ms)  SELECT * FROM `messages` WHERE (`messages`.`id` = 552)
Message Update (2.2ms) UPDATE `messages` SET `comments_count` = COALESCE(`comments_count`, 0) + 1 WHERE (`id` = 552)
Message Update (2.4ms) UPDATE `messages` SET `updated_at` = '2009-08-12 18:03:55', `delta` = 1 WHERE `id` = 552
Run Code Online (Sandbox Code Playgroud)

有没有办法只用一个SQL调用就能做到这一点?

编辑我也注意到它事先做了一个SELECT的消息.这还有必要吗?

Cha*_*ers 3

它可能会执行两次查询,因为它尚未优化。

为什么不分支并创建补丁:D