DB中每条记录加1到整数记录

时间:2012-03-10 21:54:07

标签: ruby-on-rails activerecord

对于db中的许多记录,我需要对整数列加一些值。 我试图以“干净”的方式做到这一点:

Transaction.where("account_id = ? AND date > ?", t.account_id, t.date).
update_all("account_state = account + ?", account_offset)

Transaction.where("account_id = ? AND date > ?", t.account_id, t.date).
update_all("account_state += ?", account_offset)

我收到错误:

QLite3::ConstraintException: constraint failed: 
UPDATE "transactions" SET account_state = (account_state + ?) 
WHERE (account_id = 1 AND date > '2012-03-01') AND (-10000)

但是以“肮脏”的方式工作:

Transaction.where("account_id = ? AND date > ?", t.account_id, t.date).
update_all("account_state = account + #{account_offset}")

有没有“干净”的方法来做到这一点?

1 个答案:

答案 0 :(得分:2)

update_all的第二个参数不是?的值,而是SQL请求的条件(可选)。

您可以尝试使用

Transaction.where("account_id = ? AND date > ?", t.account_id, t.date).update_all(["account_state = account + ?", account_offset])