Вопрос

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

Это было полезно?

Решение

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.

Другие советы

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.

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top