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.
0
GorillaApe
On
Given answers don't seem correct at least for Rails 5.x because it will execute SQL UPDATE that is atomic.
UPDATE .... SET counter = counter + 1
0
lobati
On
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.
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.