3

Suppose that I have a hash of hashes as following. One can use "update" to update all the records as follows.

 people = { 1 => { "first_name" => "David", "last_name" => "Freeman" }, 2 => { "first_name" => "Jeremy", "last_name" => "Stone" } .....}

 Person.update(people.keys, people.values)

This will run an UPDATE query for each record. How can I use "update_all" to achieve this which runs a single query for all the records?

Referred to (this) but couldn't find the solution.

Thanks in advance.

3
  • @SRack I couldn't figure out what should be the parameters if I need to update a few and with different values for each record. Commented Dec 1, 2017 at 11:06
  • How would a plain SQL query look like that does what you try to build with ActiveRecord? Commented Dec 1, 2017 at 11:10
  • @spickermann insert into persons(id,first_name,last_name) values (1,"David","Freeman"), (2,"Jeremy","Stone") on duplicate key update first_name=values(first_name), last_name=values(last_name); Commented Dec 1, 2017 at 11:17

1 Answer 1

2

I don't think this is possible. This is not the nature of "update_all". Imagine writing a SQL query for your required result, it will involve matching each id and then doing the required update for each id, hence contrasting it from what "update_all" does.

You should use "update_all" when performing same update over a set of tuples, but obviously in your case first_name and last_name are different for each tuple.

I think using just "update" will not affect performance much, considering the id's are indexed. However, you always have the option of writing native SQL statements.

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

Comments

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.