开发者

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 recor开发者_高级运维ds, perhaps by doing something like @users.delete?


@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


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.


yep:

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


@users.destroy_all is the simplest way


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 }


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

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


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:

  • delete_by: https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-delete_by
  • delete_all: https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-delete_all

or:

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

Which is based on destroy_all, documentation:

  • destroy_by: https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-destroy_by
  • destroy_all: https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-destroy_all

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜