Rails bulk delete items on frontend part

So when your database grows it might come in handy if you give your customers the option to bulk manipulate data in lists. I’ve got a list of products and my client told me, that they often create dozens of test items to check out things and then they delete them. Clicking one by one and, especially, waiting every time for the page to load can be tiresome. Here is my approach:

Wrap the listing table in a form

Don’t get confused by my ‘object’… err… object, it serves the purpose of enabling many models to use this listing partial. The main parts are ‘form_for’, the checkbox and the ‘submit_tag’. It is important to use an array for storing the checkbox values, or else we won’t be able to retrieve all id’s at once.

Now the form leads us to the custom controller (‘rails g controller bulk_actions’):

First of all, I’m getting the object from ‘params[:object]’ (this is why I included the hidden_field_tag in my form). Since I’m using the partial for any model, I need to know, do I delete the Post model or the Product model right now. The if-clause makes sure we only handle a bunch of items, it does not make any sense to bulk delete 1 item. Since my object is rather a string, I need to convert it to a modal constant. Then we simply iterate over each found object and destroy it. You can disregard the ‘sublevel’ part.

Now for the frontend – I wanted the delete button only to appear if two or more items are selected and be hidden elsewise. Since I’m using iChech checkboxes we need to hook up on different methods. Particularly it is ‘ifToggled’ in this case:

Add one last thing – the route

And you are ready to go!

Heavily inspired by this article.

Published by

Anton

Hello! My name is Anton. I am a passionate project manager who loves digging deep into code. You can check my Github and CodeEval. Hopefully my thoughts on management can lead you to one or another good idea.