rails update_all interpolation

943 Views Asked by At

I have a database with a lot of pets. I am looking to update the 'name' attribute by changing it's case. I have tried:

Pet.update_all(:name => Pet.name.upcase)
Pet.update_all(:name => name.upcase)
Pet.update_all(:name => :name.upcase)
Pet.update_all(:name => "#{name.upcase}")

but all of those return:

  • "PETS" for every name
  • "NAME" for every name
  • "NAME" for every name
  • invalid syntax

what am I missing here?

3

There are 3 best solutions below

2
Jorge de los Santos On

As long as you are refering to an own attribute inside of the update attribute you won't be able to do this without iterating. An option coul be:

Pet.all.each {|x| x.update(name: x.name.upcase)

Another option:

ActiveRecord::Base.connection.execute "UPDATE pets SET name = UPPER(name)"
2
Arkhitech On

Do it Rails way:

Pet.update_all(:name => "UPPER(name)")
0
tomb On

Pet.update_all('"name" = Upper("name")') works in Rails 5.2