Ragav Y
Ragav Y

Reputation: 1872

Rails routes confuses a custom destroy method with destroy method in users controller

I have a users controller with the following two destroy methods:-

  def destroy
    @user = User.find_by(params[:id])
    @user.destroy
    flash[:success] = "Account successfully closed"
    redirect_to root_path
  end

  def destroy_avatar
    @user = User.find_by(params[:id])
    @user.remove_avatar!
    @user.save
    render 'edit'
  end

The first is the default destroy method that deletes the user. The second is one that I defined to let the user delete their avatar from their user edit page.

I had the following defined in the routes.rb to get the destroy_avatar working:-

delete '/users/:id', to: 'users#destroy_avatar', as: 'destroy_avatar'
resources :users

But unfortunately when I implemented this the close account button I had on the user edit page reverted to the destroy_avatar action.

This is the call to both the actions from the view:-

.
.
.
        <% if current_user.avatar_url %>
          <%= link_to "Delete avatar", destroy_avatar_path,
              method: :delete,
              data: {:confirm => 'Are you sure?'},
              class: 'btn btn-xs btn-danger',
               "data-toggle" => "tooltip",
               "data-placement" => "right",
               "title" => "Delete avatar" %>
.
.
.
      <%= link_to "Close account", user_path(@user),
                                   method: :delete,
                                   data: {:confirm => "Are you sure?"},
                                   class: "btn btn-xs btn-danger"%>
.
.
.

I went looking to see if there is a way to get the destroy_avatar to work without using routes, but I found a way to do it with AJAX without requiring an additional route, which would actually be more convenient but I don't know Javascript and couldn't customize the code to my case.

I am still learning rails and I don't know what I don't know! So I would like to know what options I have.

Is there a way to do this without using two routes? If no, how should I customize the route for the destroy_avatar so that there is no conflict with the route for user destroy action?

Upvotes: 1

Views: 869

Answers (1)

Ragav Y
Ragav Y

Reputation: 1872

Ok, I figured it out.

Changed the route to

delete '/users/:id/destroy_avatar', to: 'users#destroy_avatar', as: 'destroy_avatar'

and from the view:

<%= link_to "Delete avatar", "/users/#{@user.id}/destroy_avatar" %>

Upvotes: 2

Related Questions