I am trying to delete an array of users but the way I have it it is deleting one by one. Is there a better way to do it?
My code is:
@users ||= User.where("clicks_given - clicks_received < ?", -5).to_a
@users.each do |user|
user.destroy
end
You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr. splice(n, 1) , with n being the index of the element to remove.
Array#select() : select() is a Array class method which returns a new array containing all elements of array for which the given block returns a true value. Return: A new array containing all elements of array for which the given block returns a true value.
You can just use Rails' built-in methods. Note that you need to wrap your query in an array (if you're interpolating variables) when using these methods.
To iterate over each one calling destroy (which will run callbacks, etc.):
User.destroy_all(["clicks_given - clicks_received < ?", -5])
Or to just delete these in the database in a single query (no iteration over each item), you can do this, but keep in mind it won't run your callbacks:
User.delete_all(["clicks_given - clicks_received < ?", -5])
You could use the destroy_all
method:
User.destroy_all("clicks_given - clicks_received < ?", -5)
Reference: http://apidock.com/rails/v3.0.5/ActiveRecord/Relation/destroy_all
I've also used the following before:
@users.map(&:destroy)
It's essentially doing the same thing as your each call, but you can avoid the boiler-plate code.
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