Forum: Ruby on Rails counter_cache is making a redundant SELECT before UPDATE

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Fernando P. (Guest)
on 2009-06-01 13:42
Hi,

I have the following code:

Message, belongs_to :topic, :counter_cache => true

topic = Topic.find_from_permalink(params[:id])

topic.messages.create(params[:message])

When the message gets created, then AR issues a supplemental SELECT to
retrieve the message's topic and then updates its messages_count. Why is
that happening?

If I do it manually:

if topic.messages.create(params[:message])
  topic.messages_count += 1
  topic.save!
end

Then I don't get this additional SELECT. Does the sql cache only work
when I do Topic.find(2) ?
Fernando P. (Guest)
on 2009-06-01 13:48
Hmm, actually I just watched the railscasts about the counter_cache, and
in his log he also has this redundant SELECT that he didn't even spot.

So I guess this could be an additional feature added to Rails to save 1
DB query.
Frederick C. (Guest)
on 2009-06-01 14:05
(Received via mailing list)
On Jun 1, 10:48 am, Fernando P. <removed_email_address@domain.invalid>
wrote:
> Hmm, actually I just watched the railscasts about the counter_cache, and
> in his log he also has this redundant SELECT that he didn't even spot.
>
> So I guess this could be an additional feature added to Rails to save 1
> DB query.

This is basically rails not knowing about inverse associations (which
it will do in the next version).
If you do do itself you should use increment_counter rather that doing
what you show above (which has a race condition).

Fred
Fernando P. (Guest)
on 2009-06-01 14:35
> This is basically rails not knowing about inverse associations (which
> it will do in the next version).
> If you do do itself you should use increment_counter rather that doing
> what you show above (which has a race condition).
>
> Fred

Thank you Frederick for your message :-)
Jeffrey L. Taylor (Guest)
on 2009-06-01 23:43
(Received via mailing list)
Quoting F. Perez <removed_email_address@domain.invalid>:
>
> Hmm, actually I just watched the railscasts about the counter_cache, and
> in his log he also has this redundant SELECT that he didn't even spot.
>
> So I guess this could be an additional feature added to Rails to save 1
> DB query.

Is the title declared unique?  Then Rails queries the DB to check that
there
is no existing record before doing the UPDATE.

HTH,
  Jeffrey
This topic is locked and can not be replied to.