Heather Stenson
Heather Stenson

Reputation: 43

Rails & Devise: User accounts not deleting

I'm using the Devise gem for the first time to authenticate users. I can sign up, log out, sign in, and edit user accounts without issues, but deleting accounts isn't working! When I click the button to delete, the JS confirmation pops up asking if I want to delete, I click yes... and then I'm redirected to the user's show page. User account is intact.

In views/devise/registrations/edit.html.erb:

<p>Unhappy? <%= button_to "Cancel my account", '/users/#{@user.id}',   data: { confirm: "Are you sure?" }, method: :destroy, class: "btn btn-danger" %></p>

In my UsersController:

  def destroy
    @user = User.find(params[:id])
    @user.destroy

    if @user.destroy
        redirect_to root_path
    end
 end

I'm still shaky on Rails routing, but in my routes.rb I have:

devise_for :users, :controllers => { registrations: 'registrations' }

as well as:

resources :users

And when I run rake routes, the two routes I think may be associated are:

DELETE /users(.:format)          registrations#destroy
DELETE /users/:id(.:format)      users#destroy

I'm pretty sure that I'm doing something wrong with the routes, but I can't see what. Any advice is appreciated!

Upvotes: 4

Views: 814

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

#config/routes.rb
resources :users, only: :destroy

#view
<%= button_to "Cancel my account", @user, method: :delete, data: { confirm: "Are you sure?" } %>

Resources

The problem you have is you're not calling the delete HTTP verb; instead, you're calling it as destroy (method: :destroy).

To give context, the HTTP protocol is populated with a series of verbs, to help you define different "actions" for a particular resource (url). Here's Wikipedia's explanation:

HTTP defines methods (sometimes referred to as verbs) to indicate the desired action to be performed on the identified resource. What this resource represents, whether pre-existing data or data that is generated dynamically, depends on the implementation of the server.

Thus when you use the resources helper in the routes of your app, you'll see which routes are generated:

enter image description here

As can be seen above, each time you declare routes for a particular resource, Rails auto populates with several predefined urls / paths. In order for your app to process your requests properly, you have to send it to the requested URL - and it has to be valid.

Upvotes: 4

Pavan
Pavan

Reputation: 33552

Change

<p>Unhappy? <%= button_to "Cancel my account", '/users/#{@user.id}',   data: { confirm: "Are you sure?" }, method: :destroy, class: "btn btn-danger" %></p>

to

<p>Unhappy? <%= button_to "Cancel my account", '/users/#{@user.id}',   data: { confirm: "Are you sure?" }, method: :delete, class: "btn btn-danger" %></p>

You should use method: :delete not method: :destroy

Upvotes: 1

Related Questions