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