Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 delete all elements of an array

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
like image 702
Tiago Veloso Avatar asked May 04 '11 21:05

Tiago Veloso


People also ask

How do you remove an element from an array array?

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.

What does .select do in Ruby?

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.


2 Answers

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])
like image 140
Dylan Markow Avatar answered Nov 09 '22 15:11

Dylan Markow


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.

like image 32
McStretch Avatar answered Nov 09 '22 16:11

McStretch