Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i do an update statement where a condition

Tags:

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.

like image 732
Matt Elhotiby Avatar asked Feb 08 '12 01:02

Matt Elhotiby


People also ask

Can you write update query with WHERE condition?

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.

How do you update a table based on a condition?

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.

Can we use WHERE with update?

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.

What is the function of a WHERE clause in an update statement?

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!


2 Answers

ActiveRecord::Relation supplies an update_all method.

Model.where(state: 'decline').update_all(state: 'deny') 
like image 51
Bradley Priest Avatar answered Sep 19 '22 12:09

Bradley Priest


You can also chain update_all off a scope such as:

book.chapters.where(state: 'draft').update_all(state: 'unpublished') 
like image 40
Kris Avatar answered Sep 20 '22 12:09

Kris