Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything like batch update in Rails?

In Java we have batch execution like the java code below:

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

how to do the same in rails ActiveRecord?

like image 579
Vijay Avatar asked Feb 10 '23 20:02

Vijay


1 Answers

You can give this a try. Seems like what you're after.

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

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

To fit the post requirements, it translates to:

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

Please note that translating the above into SQL still yields multiple queries

like image 130
Mingsheng Avatar answered Feb 13 '23 14:02

Mingsheng