在Rails中有什么类似批量更新的东西吗?

时间:2015-02-24 11:23:11

标签: mysql ruby-on-rails

在Java中,我们有批处理执行,如下面的java代码:

Statement statement = null;
statement = connection.createStatement();
statement.addBatch("update people set firstname='John' where id=123");
statement.addBatch("update people set firstname='Eric' where id=456");
statement.addBatch("update people set firstname='May'  where id=789");

int[] recordsAffected = statement.executeBatch();

如何在rails ActiveRecord中执行相同操作?

1 个答案:

答案 0 :(得分:8)

你可以尝试一下。看起来像你在追求什么。

# Updating multiple records:
people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
Person.update(people.keys, people.values)

引用:https://cbabhusal.wordpress.com/2015/01/03/updating-multiple-records-at-the-same-time-rails-activerecord/

为了满足职位要求,它转换为:

people = { 
  123 => { "firstname" => "John" },
  456 => { "firstname" => "Eric" },
  789 => { "firstname" => "May" }
}
Person.update(people.keys, people.values)

请注意,将上述内容翻译成SQL仍会产生多个查询