ruby-on-railsruby-on-rails-3transactionscountercounter-cache

Ruby on Rails -- Is a counter-cache transaction safe?


Will it handle the two people updating problem ok?

I googled and looked in the api but found nothing

Rails 3+, ruby 1.9.3


Solution

  • When using counter_cache, the record insert and the counter update are done in the same transaction. But this does not guarantee atomicity of an operation. You may have to "lock" your record in addition to avoid the two people update problem.

    See this excellent article. It's about the redis-objects gem but the first two parts perfectly explain the problem and the solution with ActiveRecord.