我可以在Rails 2.3中进行原子增量而不使用SQL吗? [英] Can I do an atomic increment in Rails 2.3 without dropping down to SQL?

查看:76
本文介绍了我可以在Rails 2.3中进行原子增量而不使用SQL吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们的应用程序中有一些经常遇到的代码,它们会增加一列,就像这样:

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?

推荐答案

您可以使用类方法increment_counter:

Customer.increment_counter :counter, customer

这将创建类似的内容:

UPDATE `customers` SET `counter` = COALESCE(`counter`, 0) + 1 WHERE (`customers`.`id` = 53)

(与customer.increment!(:counter)不是原子的方法不同,您必须将id或类的实例传递到此方法(customer)

(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)

这篇关于我可以在Rails 2.3中进行原子增量而不使用SQL吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆