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.
You use map () with splice method to Remove object from array JavaScript by id. Use indexOf () method to find the index of the item and then remove it with splice: Simple example code removes object where id is 2.
The process of deleting is called destroy in Rails. There is a reason for this, and I want to begin this guide by discussing that. Start a rails console session with the command rails c.
Explicitly Remove Array Elements Using the Delete Operator You can remove specific array elements using the delete operator: var ar = [1, 2, 3, 4, 5, 6]; delete ar; console.log(ar); alert(ar); Using the delete operator does not affect the length property.
If you want to remove multiple items that match your criteria there is a glitch. As the items are removed from the array the index still increments and the next item after your matched value is skipped. The simple solution is to modify the above example to decrement the index variable so it does not skip the next item in the array.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With