5
votes
Foo.where(:some_id => 1).update_all(:some_columnn => "1")

Is this the right way to update Foo? I don't want to do a find and update the object.

4

4 Answers

2
votes

Yes it is the right way, but remember, no callbacks or validations will be executed.

BTW, update_all accepts conditions also. Like this

Foo.update_all({:some_columnn => "1"}, {:some_id => 1})
2
votes

As of Rails 4, the conditions are no longer supplied on the update_all method, but are instead specified on the preceding collection. For example,

# updates everything, as usual
Foo.update_all(some_column: '1')

# update only the specified rows
Foo.where(some_id: 1).update_all(some_column: '1')
0
votes

It is the right approach if you don't want to instantiate an object, but keep in mind that this also means it won't perform any of your models validations or callbacks - it goes straight to a SQL update command.

Further information

0
votes

You can use conditions,according to the api of update_all

update_all(updates, conditions = nil, options = {})

So you can do:

Foo.update_all(:some_column => '1', :some_id => 1)