Ruby on Rails -- Is a counter-cache transaction safe?
Asked Answered
C

3

6

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

Campobello answered 11/8, 2012 at 1:19 Comment(0)
P
4

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.

Pneumatophore answered 1/10, 2013 at 21:47 Comment(0)
L
2

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.

Ladyinwaiting answered 13/3, 2015 at 3:23 Comment(0)
L
1

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
Lanilaniard answered 22/4, 2019 at 14:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.