Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord Update_all to variable value

I'm looking for a way to update all record with certain condition their cur_val + 100:

I have a table Suggestions with id and score fields, and I want all the entries with specific ids to receive a score bump, e.g:

Suggestion.where(id: ids_list).update_all(score: score+100)

How do I do that?

like image 289
Yossale Avatar asked Feb 01 '26 06:02

Yossale


1 Answers

Try plain SQL, read about update_all:

Suggestion.where(id: ids_list).update_all('score = score + 100')

But remember update_all not trigger Active Record callbacks or validations.

Some tips:

You can do it in Ruby but this very bad:

Suggestion.where(id: ids_list).find_each do |x|
  x.update(score: x.score + 100)
end

Things like this should happen in database.

like image 169
Philidor Avatar answered Feb 03 '26 00:02

Philidor