mah.aziz
mah.aziz

Reputation: 177

Increment all records with fixed value in rails

I want to do this

User.all.each do |user|
    user.salary = user.salary + 100
    user.save
end

I tried this User.update_all(salary: "salary + 100") but it raised that exception Mysql::Error: Incorrect integer value: 'salary + 100' for column 'salary' at row 1:

What is the best way to increment all records in rails ?

Upvotes: 3

Views: 950

Answers (2)

Mahmoud Khaled
Mahmoud Khaled

Reputation: 6276

Use this code:

User.update_all("salary = salary + 100")

Upvotes: 4

M.ElSaka
M.ElSaka

Reputation: 1294

You can simply do it like this:

User.update_all('salary = salary + 100')

Upvotes: 3

Related Questions