8

I understand one could do something like Model.destroy_all(status: "inactive"). I wish my case were this simple, but I can't do it like that. I have an encrypted string column that maps to an array of integers via the attr_encrypted gem which makes this cumbersome.

Basically, I have an array like this: array = [object1, object2, object3, object4] where each object is model object.

I want to be able to do something like Model.destroy_all(array) or Model.delete_all(array), but I am unable to do this.

I even tried the following: Model.destroy_all(array.map(&:id)) and Model.delete_all(array.map(&:id)) and I couldn't successfully delete them.

I want to be as efficient as possible and I don't think array.map(&:destroy) or array.map(&:delete) would be efficient as I'd get N calls. Should I do that and wrap it in a transaction? Is there a better way?

Update: I figured it out and included an answer down below.

1
  • You can do Model.destroy_all(id: array.map(&:id)). I believe it better optimized compared to Model.destroy(array). Commented Jun 30, 2017 at 16:12

2 Answers 2

14

Well, this is silly. Turns out I could just do:

Model.delete(array) or Model.destroy(array) where the first one doesn't do any of the callbacks and is definitely much faster, whereas the other one instantiates and performs all the callbacks.

Sign up to request clarification or add additional context in comments.

Comments

5

If you're going to call destroy_all you may as well loop through them yourself since that is what the method does itself (in order to process any callbacks).

If you're going to delete them though then this should work:

Model.where(id: array.map(&:id)).delete_all

1 Comment

Similarly but using destroy, you can do too: Model.where(id: array.map(&:id)).destroy_all

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.