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'")
Share:
22,316

Related videos on Youtube

Vijay Chouhan
Author by

Vijay Chouhan

Senior Full Stack Ruby on Rails, JavaScript Developer, ReactJs, Mobile App Develporand Team Leader.

Updated on January 22, 2022

Comments

  • Vijay Chouhan
    Vijay Chouhan over 2 years

    I want rails queries similar to:

    UPDATE users SET name="test" WHERE name="test1"
    
  • arieljuod
    arieljuod over 10 years
    that 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
    simonmorley over 10 years
    I think the first options actually depreciated now.
  • Noz
    Noz almost 10 years
    Can confirm after 15 minutes of debugging old code, the first line is deprecated in Rails 4 (wish they gave a warning!).
  • Aaronias
    Aaronias over 7 years
    I 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
    Vignan Sankati over 4 years
    How to update multiple values, can I use User.where(name: 'test1').update_all(name: 'test', email: '[email protected]')
  • arieljuod
    arieljuod over 4 years
    @VignanS, yes, you can pass as many key: value pairs as you need.
  • Vignan Sankati
    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
    arieljuod over 4 years
    I'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.