0

I am trying to update multiple rows. Some rows may have a value already. So if the value in that row was 2 and I wanted to update it with an additional 4 to make total of 6. How can I do that without querying each row for it's current value? Or must I do that?

I currently have something like thing like this.

item_match = Item.where("id IN (?)", item_match_ids).to_a
item_match.update_all(quantity: quantity)

2 Answers 2

4

If adding the same value to all records, you can use the following:

item_match.update_all("quantity = quantity + #{ quantity }")

This is much faster than updating the records individually. To be safe, you should make the quantity column non-null and set a default value. Be sure to sanitize the quantity value for SQL if it's user-supplied.

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

Comments

1

I think you must remove the to_a, leaving this way:

Item.where(id: [id1, id2, ...]).update_all(quantity: quantity)

But, if you want to add a quantity to each record you need use find each:

Item.where(id: [id1, id2, ...]).find_each do |item|
  item.update(quantity: item.quantity + quantity)
end

You will find more of find_each here

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.