Dennis Hackethal
Dennis Hackethal

Reputation: 14295

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.

Upvotes: 3

Views: 5416

Answers (2)

sekrett
sekrett

Reputation: 1275

With newer Rails do this:

Table.where(id: [4, 5, 6]).update_all("field = 'update to this'")

Upvotes: 0

Jay Truluck
Jay Truluck

Reputation: 1519

You can use the update_all method, for example:

Table.update_all("field = 'update to this'", ["id in (?)", ids])

Upvotes: 7

Related Questions