Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update multiple rows in Rails 3.2

I am trying to do this

User.find([23,45,68,123]).update_all(:is_active => true) 

but I get:

NoMethodError: undefined method `update_all' for #<Array:0x00000007493778> 

What would be the correct syntax? I would rather not iterate through each one if I don't have to.

like image 505
timpone Avatar asked Mar 14 '13 23:03

timpone


People also ask

How to update multiple rows in Rails?

Rails provides a built-in create method for adding multiple records in single line of code or in more technical term “batch create”. For update, if we want to update attributes with same value for all available records then we can do so with the method update_all .

How to update all records in Rails?

update_all({:new_column => "bar"}, {:old_column_1 => nil}) . It will update all records that has a nil value on 'old_column_1' column.


Video Answer


1 Answers

find returns an array, so you cannot use update_all.

To solve the problem, I think you can use where, which returns an ActiveRecord::Relation, so the update_all should work:

User.where(:id =>[23,45,68,123]).update_all(:is_active => true) 

http://apidock.com/rails/ActiveRecord/Relation/update_all

I hope it helps...

like image 52
gabrielhilal Avatar answered Oct 02 '22 18:10

gabrielhilal