How to write update all conditionally queries in rails4
22,316
Solution 1
User.update_all({name: 'test'},{name: 'test1'}) # deprecated since Rails 4
or
User.where(name: 'test1').update_all(name: 'test')
Solution 2
User.where("name like 'test1'").update_all("name = 'test'")
Related videos on Youtube
Author by
Vijay Chouhan
Senior Full Stack Ruby on Rails, JavaScript Developer, ReactJs, Mobile App Develporand Team Leader.
Updated on January 22, 2022Comments
-
Vijay Chouhan over 2 years
I want rails queries similar to:
UPDATE users SET name="test" WHERE name="test1"
-
arieljuod over 10 yearsthat would generate 'UPDATE users SET name="test" WHERE name LIKE "test1"', it's the same result, but not the same query the OP asked for EDIT: not the same result, LIKE is caseunsensitive, it will update also rows with name TEST1 for example
-
simonmorley over 10 yearsI think the first options actually depreciated now.
-
Noz almost 10 yearsCan confirm after 15 minutes of debugging old code, the first line is deprecated in Rails 4 (wish they gave a warning!).
-
Aaronias over 7 yearsI would also like to point out that this statement is run as a single update where clause instead of a single select where and then an update statement.
-
Vignan Sankati over 4 yearsHow to update multiple values, can I use
User.where(name: 'test1').update_all(name: 'test', email: '[email protected]')
-
arieljuod over 4 years@VignanS, yes, you can pass as many key: value pairs as you need.
-
Vignan Sankati over 4 years@arieljuod I tried it but it updates only name, but if I try to update those two variables separately then it gets updated. name & email are attr_accessible on active record too and also verified the email can have null
-
arieljuod over 4 yearsI'm not sure what could be causing you troubles, update_all accepts a hash and you can update multiple columns at the same time. Just tried it to double check and it works, it creates an SQL UPDATE query setting the columns' values, you can check the query on the logs or running that code on a rails console.