In Rails 3, how do I update an attribute with a condition like:
Model.where("state == 'decline'").all.update_attribute(:state, 'deny')
This is definitely wrong, but I am drawing a blank on how to achieve this.
The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE clause with the UPDATE query to update the selected rows, otherwise all the rows would be affected.
UPDATE syntax:UPDATE table_name SET column_name = value WHERE condition; To perform the above function, we can set the column name to be equal to the data present in the other table, and in the condition of the WHERE clause, we can match the ID.
WHERE clause can be used with SQL UPDATE to add conditions while modifying records. Without using any WHERE clause, the SQL UPDATE command can change all the records for the specific columns of the table.
The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!
ActiveRecord::Relation supplies an update_all
method.
Model.where(state: 'decline').update_all(state: 'deny')
You can also chain update_all
off a scope such as:
book.chapters.where(state: 'draft').update_all(state: 'unpublished')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With