[英]ActiveRecord Update_all to variable value
I'm looking for a way to update all record with certain condition their cur_val + 100: 我正在寻找一种在一定条件下更新其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, eg: 我有一个带有ID和得分字段的表格建议,并且我希望所有具有特定ID的条目都收到得分的提高,例如:
Suggestion.where(id: ids_list).update_all(score: score+100)
How do I do that? 我怎么做?
Try plain SQL
, read about update_all
: 尝试普通的
SQL
,了解有关update_all
:
Suggestion.where(id: ids_list).update_all('score = score + 100')
But remember update_all
not trigger Active Record
callbacks or validations. 但是请记住,
update_all
不会触发Active Record
回调或验证。
You can do it in Ruby
but this very bad: 您可以在
Ruby
完成此操作,但这非常糟糕:
Suggestion.where(id: ids_list).find_each do |x|
x.update(score: x.score + 100)
end
Things like this should happen in database. 这样的事情应该在数据库中发生。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.