gpt4 book ai didi

javascript - Ruby on Rails : Validate a user has selected a checkbox

转载 作者:行者123 更新时间:2023-12-03 04:58:53 25 4
gpt4 key购买 nike

在我的 RoR 应用程序中,我有一个记录表,其中每条记录都有一个复选框,以便用户可以选择和删除多个记录。

这通过以下代码实现。

<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

路线:

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

但是,这缺乏验证,用户当前可以在不选择任何复选框的情况下单击删除按钮 - 这会导致系统出错。

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

最佳答案

您可以使用 Flash 消息

在 Controller 中执行

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

在 View 中添加上面的表格

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

关于javascript - Ruby on Rails : Validate a user has selected a checkbox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42315034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com