Multiple delete by selecting checkboxes

Hi,

I would like to implement a simple list where I can check multiple items ( checkbox ), and click a single button to delete all the selected items.

After watching the video on the main page, and hearing that they built ‘hey.com’ using Hotwired and Stimulus, it looks like they achieve the same sort of functionality for selecting multiple emails and ‘setting them aside’.

Could someone please explain if this is possible, and a basic method to accomplish it if so.

This is definitely possible. You’ll need to hand-build the relevant form elements, because there’s no helper for this pattern, although it might be possible to use the collection_check_boxes helper, I’ve never tried it for this.

<%- @collection.each do |member| -%>
<%= check_box_tag 'ids[]', member.id, id: nil, class: 'multiple-checkbox' %> 
(Plus a label for each, naturally)
<%- end -%>
<%= hidden_field_tag 'ids[]', nil, id: nil %>

You’ll get an array named ids containing the ID of each checked checkbox. The hidden field is there to ensure that you can uncheck the last checkbox and still get a result. (HTML forms do not submit un-checked checkboxes at all.)

You’ll be able to use the value of that field in your controller as the array of ids to delete. I leave that part of the exercise up to you. Also, setting the ID to nil just ensures that the HTML is valid. If you don’t do that, then you will end up with more than one HTML element with the same ID, which makes it very difficult to do anything beyond showing it in a browser. (JavaScript will do confusing things at best if you try to rely on that ID in a DOM selector.)

Hope this helps,

Walter

Hi Walter

Thank you very much for the reply. I believe if I understood everything, the entire list would have to be wrapped in a form?

Yes, but if that is a deal-breaker for your layout, you can also have a form as an island, containing nothing except the submit button, and then add the ID of that form to each of the check boxes (and the hidden field) like this:

<%= check_box_tag 'ids[]', member.id, id: nil, form: 'the_form_id', class: 'multiple-checkbox' %>

That allows those fields to not be nested, if that’s something you need, while still being considered as “children” of the form (so they will submit).

Walter

Thank you very much. I was actually busy testing whether you could have an empty form and link the fields to it with an ID.

Thanks again for all the help.