Ahsan Agwan
Ahsan Agwan

Reputation: 3

How to destory all users but current user(admin) in ruby

I have this setup where it destroys all users but i want it not to destroy current user which is admin.

controller.

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

route:

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

I know I have to add something to the controller just don't know what to add

Upvotes: 0

Views: 43

Answers (1)

Joel Blum
Joel Blum

Reputation: 7888

I'm assuming you have access to the current_user in your controller (or if not that, you know the id of the current user somehow

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

Note: In Rails 7 you will also be able to do

 User.excluding(current_user).destroy_all

Which is a bit nicer maybe, but this doesn't work yet.

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

Upvotes: 1

Related Questions