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.
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 .
update_all({:new_column => "bar"}, {:old_column_1 => nil}) . It will update all records that has a nil value on 'old_column_1' column.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With