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.

1
  • short answer is no. because every transaction has to be atomic and isolated in a relational database. Commented Dec 10, 2013 at 23:58

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.