0

I am using Model.increment_counter(:c, 11) in order to avoid race conditions when incrementing a column (See related: How do I consistently increase a counter cache column?)

I notice however that for the following code:

@order = Order.find(11)
p @order.c # This prints 4
Order.increment_counter(:c, 11)
p @order.c # This still prints 4
@order.reload
p @order.c # This prints 5

Why is it necessary to reload the object after doing the update? Why does AR not show that change directly?

Community
  • 1
  • 1
Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

1 Answers1

3

The issue here is the following:

  • you have an object in memory
  • you call a class method with the id of the object
  • you expect the in memory object to be updated

It cant be, the class method knows nothing about your in memory object.

Why dont you set the value directly on your model property if you have it?

apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • I am using the class method because I want to take advantage of the lock mechanism it provides for the increment operation. I am having race condition problems for different threads that are trying to update that column for that object at the same time. – Hommer Smith Jul 14 '14 at 16:57