We have some often-hit code in our app that increments a column, like so:
if (r = customer.find_or_generate_reminder)
r.counter += 1
r.save!
end
We're getting lock wait timeouts, so I'm thinking about making this an atomic operation. Naively, what I want to do looks like this:
if (r = customer.find_or_generate_reminder)
connection.excute('UPDATE customer_reminders SET counter=counter+1, updated_at=now() WHERE id = ' + r.id)
end
Is there a ruby-world way of doing the same thing?
You can use the class method increment_counter
:
Customer.increment_counter :counter, customer
That'll create something like:
UPDATE `customers` SET `counter` = COALESCE(`counter`, 0) + 1 WHERE (`customers`.`id` = 53)
(you have to pass either an id or an instance of the class into this method (customer
) unlike the customer.increment!(:counter)
method which is not atomic)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With