Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 614
Michael Durrant Avatar asked Aug 11 '12 01:08

Michael Durrant


Video Answer


2 Answers

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.

like image 80
Cédric Darné Avatar answered Sep 19 '22 12:09

Cédric Darné


Short answer: no. As Cédric mentions, Rails updates the counter_cache inside of a transaction, so if you say, have a background process that updates the same record, you'll find yourself getting deadlock errors unless you run both updates using a with_lock block on the record.

like image 33
lobati Avatar answered Sep 21 '22 12:09

lobati