user1483441
user1483441

Reputation: 649

How can I add the functionality in Rails where a user can delete himself or herself?

I have the following code in my Users controller in Rails to let users delete themselves:

def delete_account
User.find(params[:id]).destroy
flash[:success] = "Your account has been deleted."
redirect_to root_path
end

Now, I'm unsure of how to add the proper route to my route.rb file and then add the button correctly into my user settings view. For my route file I have the following code:

match '/delete_account' to: 'users#delete_account'

And in my settings view file I have the following code to add a button for the delete_account action in the view:

<%= link_to class: "btn btn-danger", delete_account_path %>\

Any help you can provide in implementing the correct route and embedded ruby in my view would be greatly appreciated. Sorry if this is an easy error to fix; I'm a beginner developer, and this has been giving me some trouble.

Upvotes: 0

Views: 84

Answers (1)

Jason Kim
Jason Kim

Reputation: 19031

I think it's better to use RESTful way.

Rename your method to destroy in controller.

In your routes.rb,

resources :users or match '/delete_account', to: 'users#destroy'

In the view, say in show.html.erb,

<%= link_to 'Delete', @user, confirm: 'Are you sure?', method: :delete %>

And obvious your show action should find the right user,

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

Upvotes: 3

Related Questions