Is there anything like batch update in Rails?

mysql, ruby-on-rails

Solution

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

Problem

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?

Original source