samedi 18 février 2017

Ruby on Rails: Validate a user has selected a checkbox

In my RoR application, I have a table of records with a checkbox against each record so that the user can select and delete multiple records.

This works through the following code.

<table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example">
    <thead>
        <tr>
            <th></th>
            <th>First name</th>
            <th>Surname</th>
            <th>Email</th>
            <th>Subscription</th>
            <th>Emails Received</th>
            <th colspan=3>Available Actions</th>
        </tr>
    </thead>
    <%= form_tag destroy_multiple_contacts_path, method: :delete do %>
    <tbody>
        <% @contacts.each do |contact| %>
            <tr class="odd gradeX">
                <td><%= check_box_tag "contact_ids[]", contact.id %></td>
                <td><%= contact.firstname %></td>
                <td><%= contact.surname %></td>
                <td><%= contact.email %></td>
                <td><%= human_boolean(contact.subscription) %></td>
                <td><%= contact.recipients.count %></td>
                <td><%= link_to 'Show', contact_path(contact) %></td>
                <td><%= link_to 'Edit', edit_contact_path(contact) %></td>
                <td><%= link_to 'Destroy', contact_path(contact), method: :delete, data: { confirm: 'Are you sure?' } %></td>
            </tr>
        <% end %>
    </tbody>
</table>

    <%= submit_tag "Delete Selected", {:class => "btn btn-danger btn-sm" } %>
<% end %>

Controller:

def destroy_multiple
    Contact.destroy(params[:contact_ids])
    redirect_to contacts_path
end

Routes:

resources :contacts do
  collection do
     delete 'destroy_multiple'
  end
end

However this is lacking validation and users are currently able to click the delete button without any checkbox being selected - this causes the system to error.

Is it possible to display an error message if the user clicks delete without selecting a checkbox or to only allow a user to click delete if they have selected a checkbox?




Aucun commentaire:

Enregistrer un commentaire