Rails 3 removes all elements of an array

I am trying to delete an array of users, but as it is, it is deleted one by one. Is there a better way to do this?

My code is:

@users ||= User.where("clicks_given - clicks_received < ?", -5).to_a @users.each do |user| user.destroy end 
+7
source share
2 answers

You can use the built-in Rails methods. Note that when using these methods, you need to wrap your request in an array (if you interpolate the variables).

Iterate over each destroy call (which will trigger callbacks, etc.):

 User.destroy_all(["clicks_given - clicks_received < ?", -5]) 

Or just delete them in the database in one query (without iterations for each element), you can do this, but keep in mind that it will not trigger your callbacks:

 User.delete_all(["clicks_given - clicks_received < ?", -5]) 
+12
source

You can use the destroy_all method:

 User.destroy_all("clicks_given - clicks_received < ?", -5) 

Link: http://apidock.com/rails/v3.0.5/ActiveRecord/Relation/destroy_all

I also used the following:

 @users.map(&:destroy) 

This essentially does the same as your every call, but you can avoid the boiler room code.

+10
source

All Articles