[英]Using current_user and other Devise Helpers in the rails console
[英]Delete other user except current_user in rails app using devise gem
我试图列出所有正在使用我的应用程序的用户,并仅删除我想要的那些用户。 但是每次我尝试删除用户时,它都会通过localhost:3000/users.2
而不是localhost:3000/users/2
。
而且它不会删除选定的用户,而是删除当前用户。 但我不想删除当前用户。
我没有修改任何控制器或模型,只是在视图中使用了以下代码来列出和删除用户。
<table class="table table-hover table-striped">
<thead>
<tr class="bg-primary">
<th>S.N.</th>
<th>Name</th>
<th>Email</th>
<th>Created at</th>
<th>Action</th>
</tr>
</thead>
<% @users.each_with_index do |u, i| %>
<% if current_user.email != u.email %>
<tbody>
<tr>
<td><%= (@page.to_i - 1) * @perpage + i+1 %></td>
<td>
<% if u.first_name.present?%>
<%= u.first_name.slice(0, 1).capitalize + u.first_name.slice(1..-1) %>
<% end %>
<% if u.middle_name.present? %>
<%= u.middle_name.slice(0, 1).capitalize + u.middle_name.slice(1..-1) %>
<% end %>
<% if u.last_name.present? %>
<%= u.last_name.slice(0, 1).capitalize + u.last_name.slice(1..-1) %>
<% end %>
</td>
<td>
<%= u.email %>
</td>
<td>
<%= u.created_at %>
</td>
<td>
<a data-confirm="Are you sure to delete" rel="nofollow" data-method="delete" href="<%= user_registration_path(u)%>">
<span class="fa-delete">
<i class="fa fa-trash fa-th-large fa-2x"></i>
</span>
</a>
</td>
</tr>
</tbody>
<% end %>
<% end %>
</table>
当我尝试删除current_user以外的其他用户时出现错误
只需使用<% unless u == current_user %>
检查当前用户, <% unless u == current_user %>
删除链接
您可以向current_user显示其他数据
<% unless u == current_user %>
<a data-confirm="Are you sure to delete" rel="nofollow" data-method="delete" href="<%= user_registration_path(u)%>">
<span class="fa-delete">
<i class="fa fa-trash fa-th-large fa-2x"></i>
</span>
</a>
<% end %>
如果您不想显示任何数据
更换
<% if current_user.email != u.email %>
与
<% unless current_user == u %>
如果您只是尝试删除用户,那么我认为您已经拥有了相应的逻辑,只需更改link_to
helper方法a
标签即可:
<% unless u == current_user %>
<%= link_to user_registration_path(u), method: :delete, confirm: "Are you sure to delete?", rel: "nofollow" do %>
<span class="fa-delete">
<i class="fa fa-trash fa-th-large fa-2x"></i>
</span>
<% end %>
<% end %>
这种方式更干净,也更具讽刺意味
您试图删除用户的路由是Devise随附的,仅用于删除当前用户。 要删除任何用户,您必须创建一个其中具有销毁操作的新控制器。 之后,将此控制器/操作添加到您的路由中,然后您将能够通过使用新路由来删除所需的任何用户。
控制器示例:
class UsersController < ApplicationController
def destroy
user = User.find(params[:id])
if current_user != user
if user.destroy
flash[:success] = "Successfully deleted"
else
flash[:error] = "Error"
end
end
redirect_to your_users_path
end
end
在您的路线中:
match 'users/:id' => 'users#destroy', :via => :delete, :as => :admin_destroy_user
然后在创建链接时:
<%= link_to "Destroy", admin_destroy_user_path(user), method: :delete, data: { confirm: "You sure?" } %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.