Counter_cache is making a redundant SELECT before UPDATE


#1

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) ?


#2

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


#3

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.


#4

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 :slight_smile:


#5

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