mardi 16 janvier 2018

Rails: Select items via checkboxes and then do something with them when button is pressed?

My end goal is to present a list of various active record objects, let users select some of these via checkboxes, and then finally press a button to trigger some action to be taken on them.

As an example, let's say these active record objects represent songs, and I'd like a user to be able to select a list of songs and then click a "Save Playlist" button to pass the list of selected songs to some function in my controller.

I believe that I would first start with a list of songs in my view that have checkboxes next to them. I think it would look something like this:

<table class='table table-bordered'>
  <thead>
    <tr>
      <th style="width:30px;"> Save to Playlist? </th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>
    <% @songs.each do |song| %>
      <tr>
        <td><%= check_box( "songs_selected", "selected_songs[]", { multiple: true }, song.id, nil) %>
        <td><%= song.name %></td>
      </tr>
    <% end %>
  </tbody>
</table>

If I'm understanding the check_box code correctly, what I have should allow me to pass a selected_songs array with the ID's of songs I have selected.

I'm just not positive how to finish this off with a button that's linked to the checkboxes so that when it's pressed it will actually pass that array to a method in my controller.

Any input is appreciated, even if it's pointing out that my design is somehow flawed and there's some better way to do it. Thanks!




Aucun commentaire:

Enregistrer un commentaire