Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using :counter_cache and :touch in the same association

I have a Comment model that belongs_to a Message. In comments.rb I have the following:

class Comment < ActiveRecord::Base
  belongs_to :message, :counter_cache => true, :touch => true
end

I've done this because updating the counter_cache doesn't update the updated_at time of the Message, and I'd like it to for the cache_key.

However, when I looked in my log I noticed that this causes two separate SQL updates

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

Is there any way this can be done with only one SQL call?

Edit I also noticed that it does a SELECT of the Message beforehand. Is that also necessary?

like image 853
Matt Grande Avatar asked Aug 12 '09 18:08

Matt Grande


1 Answers

It probably does two queries because it's not been optimised yet.

Why not branch and create a patch :D

like image 178
Chalkers Avatar answered Sep 20 '22 03:09

Chalkers