Atomic conditional counter update with ActiveRecord in Rails without transaction

Yes there is Table.update_counters(record.id, :my_counter => by_count) . But that’s not conditional – for example I want to update counter only if result will be >= 0. Atomically.

You can try something like

but it’s not really atomic operation (unless you wrap in transaction with row lock, which I don’t like).

And if you try this

you will find it doesn’t really care about the where condition and it ignore it.

So what can I do? Right, I’m not, surprisingly, limited to predefined Rails methods but I have whole Ruby and ActiveRecord to act as my slave, not master. Little instance method in my model definition will do the job:

Let me know what would you improve in comments ;)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">