Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple rows with one query in rails

The following Rails code results in 6 queries

people = { 1 => { "name" => "David" }, 2 => { "name" => "Jeremy" }, 3 => { "name" => "Tom" } }
Person.update(people.keys, people.values)

It will do TWO queries per updated row. One select and one update.

Is there a way to do the same task in Rails 4 with only one query (or only two queries)?

There are some information here on how to do it in MySQL, but not Rails: Multiple Updates in MySQL

Thanks.

like image 672
user2725109 Avatar asked Dec 10 '13 23:12

user2725109


1 Answers

No, but not for the reason @Sam D gave.

It's because if you go through ActiveRecord, it's because you want to run validations, callbacks, etc. on the objects being updated. These validations and callbacks are not defined for a collection of objects.

You might say, "I don't care if they run." And that's fine. That's why rails gives you the ability to mass update through SQL directly.

like image 163
Kaleidoscope Avatar answered Oct 27 '22 02:10

Kaleidoscope