0

I want a method to reduce every value in a column (credit) by a specified amount. I have tried:

User.all.map! {|user| user.credit -= 50} 

which just maps the credit, rather than the user. I feel like the correct answer is to use

User.update_all(something)

but I don't know how to update a value relative to its previous value using this method.

This seems like a common requirement so I'm guessing there's a standard approach.

3 Answers 3

5

You can pass string to update_all like in this example:

User.update_all("credit = credit - 50")

SQL which will be exectued:

UPDATE "users" SET credit = credit - 50
Sign up to request clarification or add additional context in comments.

1 Comment

Note that validations and callbacks are not invoked in this case.
1

You can update User.all, just iterate on all the rows and don't forget to save each record:

User.all.each do |user|
  user.credit = user.credit - 50
  user.save!
end

but the more efficient way would be updating all the rows in the database. You can issue an SQL like:

UPDATE users SET credit = credit - 50;

1 Comment

find_each is generally preferably when iterating over all records, since it batches the fetches.
1

You should use either update_all, as suggested by @sufleR, or find_each:

User.find_each{ |user| user.update!(credit: uuser.credit - 50) }

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.