7

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.

Community
  • 1
  • 1
user2725109
  • 2,286
  • 4
  • 27
  • 46
  • short answer is no. because every transaction has to be atomic and isolated in a relational database. – Sam Dec 10 '13 at 23:58

1 Answers1

6

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.

Kaleidoscope
  • 3,609
  • 1
  • 26
  • 21
  • Kaleidoscope, thank you for your explanation. As you mentioned, I don't care if validations and callbacks run. Do you have a link/reference for mass update through SQL in rails? Thanks. – user2725109 Dec 11 '13 at 06:30
  • 3
    http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-update_all – Kaleidoscope Dec 11 '13 at 13:13