开发者

Rails 3 delete all elements of an array

I am tryin开发者_运维知识库g 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 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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜