7

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

2 Answers 2

12

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])
Sign up to request clarification or add additional context in comments.

4 Comments

@dmarkow, I was just updating my answer with destroy_all as well - not trying to copy your answer.
And I have upvoted you both. However it said that delete_all and destroy_all can not take two arguments.
It's working. If I have no callbacks, isn't it better to wipe them out with a single query?
Yes, with no callbacks, dependencies, etc., it will be much quicker, especially with many records. Otherwise, an ActiveRecord object is instantiated for every single record.
10

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.