[英]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.