更新于一体的ActiveRecord事务Rails中多条记录 [英] Update multiple records in one ActiveRecord transaction in Rails

查看:247
本文介绍了更新于一体的ActiveRecord事务Rails中多条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何更新/保存模型的多个实例一炮打响,在使用Rails的事务块?

How can I update/save multiple instances of a model in one shot, using a transaction block in Rails?

我想更新值数百记录;的值是为每个记录不同。这是的没有的一个属性的大规模更新情况。 Model.update_all(ATTR:值)是不适合在这里。

I would like to update values for hundreds of records; the values are different for each record. This is not a mass-update situation for one attribute. Model.update_all(attr: value) is not appropriate here.

MyModel.transaction do
    things_to_update.each do |thing|
        thing.score = rand(100) + rand(100)
        thing.save
    end
end

保存似乎发出它自己的事务,而不是分批更新到周围的事务。我希望所有的更新要在一个大的交易。

save seems to issue it's own transaction, rather than batching the updates into the surrounding transaction. I want all the updates to go in one big transaction.

我怎样才能做到这一点?

How can I accomplish this?

推荐答案

说你知道你想要把东西与IDS 1,2,3有得分,2,8,和64(而不是仅仅随机数),您可以:

Say you knew that you wanted to set the things with ids 1, 2, and 3 to have scores, 2, 8, and 64 (as opposed to just random numbers), you could:

UPDATE 
  things AS t
SET
  score = c.score
FROM 
  (values
    (1, 2),
    (2, 30),
    (4, 50)
  ) as c(id, score) 
 where c.id = t.id;

所以使用Rails,你会使用的ActiveRecord :: Base.connection来#执行来执行类似上述的块,但与插入正确的值的字符串。

So with Rails, you'd use ActiveRecord::Base.connection#execute to execute a block similar to the above, but with the correct value string interpolated.

这篇关于更新于一体的ActiveRecord事务Rails中多条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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