Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - update directly in SQL

Delving into the documentation and the api, I seem to be missing how to update one field in multiple rows at once.

Something like

Table.select(:field).update("update to this").where(id: 4,5,6)

would be nice.

Does something like this exist? It would be much better than having to store everything in an array, set it to a value, and calling save every time.

like image 783
weltschmerz Avatar asked Feb 03 '26 06:02

weltschmerz


2 Answers

You can use the update_all method, for example:

Table.update_all("field = 'update to this'", ["id in (?)", ids])
like image 90
Jay Truluck Avatar answered Feb 05 '26 19:02

Jay Truluck


With newer Rails do this:

Table.where(id: [4, 5, 6]).update_all("field = 'update to this'")
like image 27
sekrett Avatar answered Feb 05 '26 20:02

sekrett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!