Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I delete an array of ids/objects in Rails from my DB?

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.

like image 765
David Avatar asked Nov 04 '14 03:11

David


People also ask

How to remove object from array by id in JavaScript?

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.

What is the process of deleting called in rails?

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.

How do I remove a specific element from an array?

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.

How do I remove multiple items from an array of items?

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.


2 Answers

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.

like image 119
David Avatar answered Oct 19 '22 23:10

David


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
like image 22
Philip Hallstrom Avatar answered Oct 20 '22 00:10

Philip Hallstrom