2017-02-18 78 views
0

在我的RoR应用程序中,我有一个记录表格,每个记录都有一个复选框,以便用户可以选择和删除多个记录。Ruby on Rails:验证用户选择了一个复选框

这可以通过下面的代码。

<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 %> 

控制器:

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

路线:

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

然而,这是缺乏验证和用户现在可以点击删除按钮没有任何复选框被选中 - 这会导致系统错误。

如果用户在未选中复选框的情况下单击删除,或仅允许用户在已选中复选框时单击删除,是否可以显示错误消息?

+0

@KevalGohil,并提出可能是最简单和最快的解决方案。你可能会更喜欢Java脚本,但我建议把东西放在控制器中可能要容易得多,速度要快得多。 – BKSpurgeon

回答

1

您可以使用Flash消息

在控制器做

def destroy_multiple 
    if params[:contact_ids].blank? 
     flash[:notice] = "No contacts selected" 
     redirect_to :back 
    else 
     Contact.destroy(params[:contact_ids]) 
     redirect_to contacts_path 
    end 
end 

在视图中添加上述表

<% if flash[:notice] %> 
    <div class="notice"><%= flash[:notice] %></div> 
<% end %> 
0

我建议一些JavaScript的方法是春季介意你”已标记此内容的广告内容为javascript

  1. 禁用删除按钮,并且只有勾选复选框后才启用该按钮。这需要在每个复选框中添加一个eventListener,以检查每次用户与复选框交互时是否勾选了任何复选框,然后适当地启用/禁用该按钮。

  2. 将事件监听器添加到启用按钮。提交时,确保至少选中一个复选框或不提交表单并显示相应的消息。

这是一个基本的实现第二种方法

$(function() { 

    function noContactSelected(){ 
    var checkboxes = Array.from(document.querySelectorAll('input[type=checkbox]')); 
    var checked = checkboxes.filter(function(checkbox) { return checkbox.checked}) 
    return checked.length == 0; 
    } 

    function showNoneCheckedMsg(){ 
    var message = document.createTextNode('Please check at least one contact'); 
    document.querySelector('.error').appendChild(message); 
    } 

    $(".btn").click(function(event){ 
    if (noContactSelected()){ 
     event.preventDefault(); 
     showNoneCheckedMsg(); 
    } 
    }); 

}); 

在视图中,您将需要包括AP或class="error"

div元素始终建议您实现服务器端验证,Keval Gohil的回答地址,如果用户没有启用javascript。