如何在ruby中删除除当前用户(admin)之外的所有用户



我有这样的设置,它会破坏所有用户,但我希望它不要破坏当前的管理员用户。

控制器。

def remove_all
User.destroy_all 
redirect_to(admin_users_path, { flash: { success: 'You have wiped all the data on the website!' } })
end

navigation.html

<%= link_to "Nuke Button", remove_all_profiles_path, :method => :get %>

路线:

resources :profiles do
member do
get :delete
end
collection do
get 'remove_all'
end
end

我知道我必须在控制器上添加一些东西,只是不知道该添加什么

我假设您有权访问控制器中的current_user(或者,如果没有,您不知何故知道当前用户的id

User.where.not(id: current_user.id).destroy_all

注意:在Rails7中,您还可以进行

User.excluding(current_user).destroy_all

这可能有点好,但这还不起作用。

https://blog.saeloun.com/2021/03/08/rails-6-1-adds-excluding-to-active-record-relation.html

最新更新