Is there something like a batch update in Rails?

In Java, we do batch execution, for example, java code:

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 ActiveRecord rails?

+4
source share
1 answer

You can try. Looks like what you need.

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

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

To meet the requirements for messages, it is converted to:

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

Please note that when translating the above word into SQL, several queries are still executed

+8
source

All Articles