AnApprentice
AnApprentice

Reputation: 110950

Rails, given an array of items, how to delete in the console

Given the following:

@users = User.where(:state => 1)

which 15 for: @users.length

In the rails console, is there a way to then delete all those records, perhaps by doing something like @users.delete?

Upvotes: 7

Views: 12409

Answers (7)

vvo
vvo

Reputation: 2883

In case someone need this. In Rails 6, if you already know what you want to delete and you want to do it in an efficient way on many records, you can use either:

Model.delete_by(id: array_of_id, other_condition: value)

Which is based on delete_all, documentation:

or:

Model.destroy_by(id: array_of_id, other_condition: value)

Which is based on destroy_all, documentation:

The difference is that delete_by will not run callbacks, validations nor will it delete dependent associations. While destroy_by will do all of that (but in a slower way). So it really depends on what you want to achieve for your application.

Both of those methods should be prefered over .where.something because they will create a single SQL query, not multiple of them.

Upvotes: 0

rlasch
rlasch

Reputation: 1039

Destroy all is the simplest way. Here is the syntax:

User.destroy_all(id: [2, 3])

Upvotes: 0

brianfalah
brianfalah

Reputation: 191

the destroy_all or delete_all will execute a query like this: DELETE FROM USERS, so it will remove all the records in the table!! not only the records of the objects in the array! So I think the best way is User.delete @users.map { |u| u.id }

Upvotes: 0

test
test

Reputation: 46

@users.destroy_all is the simplest way

Upvotes: 2

fl00r
fl00r

Reputation: 83680

@users = User.where(:state => 1)

The simplest way is to use destroy_all or delete_all:

@users.destroy_all
# OR
@users.delete_all

That's all

Upvotes: 14

Michelle Tilley
Michelle Tilley

Reputation: 159095

Your model class has a delete method (and a destroy method) that can take a single ID or a an Array of IDs to delete (or destroy). Passing an array will issue only a single DELETE statement, and is the best option in this case.

User.delete @users.map { |u| u.id }
# or
User.destroy @users.map { |u| u.id }

Note that when you call destroy on an ActiveRecord model, it creates an instance of the record before deleting it (so callbacks, etc. are run). In this case, since you already have fully instantiated objects, if you really do want to call destroy (instead of delete), it is probably more performant to use the method in J-_-L's answer and iterate over them yourself.

Upvotes: 6

J-_-L
J-_-L

Reputation: 9177

yep:

@users.each{ |u| u.destroy }

Upvotes: 2

Related Questions