0

Lets say I have some Users and I want to update their ages because I put them in wrong at first. I could do them one at a time as:

User.find(20).update(age: 25)

But can I pull the users with an array, and then update each individual with the corresponding place in another array? I'm imagining something like:

User.find([20,46,78]).update_all(age: [25, 50, 43])

I have a list of User ids and what their correct ages are supposed to be, so I want to change the existing ones for those users. What's the best way to do this?

1 Answer 1

1

One way of doing this, if your backing storage is MySql/Maria you can do something like this:

arr = { 1 => 22, 2 => 55}.map { |id, age| "(#{id}, #{age})" }
User.connection.execute("INSERT into users (id, age) VALUES #{arr.join(',')} ON DUPLICATE KEY UPDATE age = VALUES(age)")

This is assuming your table name is users. Be careful. Since SQL is manually composed, watch out for injection problems. Depends on what you need, this solution might or might not work for you. It for the most part bypasses the ActiveRecord, so you will not get any validation or callbacks.

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.