Reputation: 11
I am building a simple admin page and I can't get a button to delete the user from the record and refresh the page. Confusingly, the button will make a POST request instead of a DELETE request so my "toggle_admin" function will trigger in my controller instead. I have the route set up correctly to handle a delete request so I am stumped.
index.html.erb
<th><%= button_to "Toggle", :method=> :post, params: {user_id: user.id} %></th>
<th><%= button_to "Destroy", :method=> :delete, params: {user_id: user.id} %></th>
pages_controller.rb
def toggle_admin()
selected = User.find(params[:user_id])
puts selected
selected.admin = !selected.admin
selected.save
redirect_to "/pages/admin"
flash[:success] = "User admin rights sucessfully toggled"
end
def destroy
selected = User.find(params[:user_id])
selected.destroy
redirect_to "/pages/admin"
end
routes.rb
get '/pages/admin', to: "pages#index"
post '/pages/admin', to: "pages#toggle_admin"
delete '/pages/admin', to: "pages#destroy"
Console (When clicking the button to destroy)
Started POST "/pages/admin?id=1&method=delete" for #### at 2022-09-19 14:55:06 -0700
Processing by PagesController#toggle_admin as TURBO_STREAM
Parameters: {"authenticity_token"=>"[FILTERED]", "id"=>"1", "method"=>"delete"}
Completed 404 Not Found in 1ms (ActiveRecord: 0.0ms | Allocations: 933)
Upvotes: 0
Views: 143
Reputation: 11
To solve:
I needed to change the route to
delete '/pages/admin', to: "pages#destroy", :as => :user
And the button to:
<th><%= button_to "Destroy", user, :method => :delete, params: {user_id: user.id} %></th>
Upvotes: 1