Search code examples
ruby-on-railsrubydevisecancan

Need to allow user to delete own profile - Rails, Devise, Cancan


After several hours of trying to piece together code I've found here and across the web, I think I've gotten to the point where I may have made a mess of my code. Please let me know if you need any other snippets, I will try to include the pertinent code below. There are separate models for the user and the profile.

Thanks for your help!

EDIT: rake route shows this route: admin_destroy_user DELETE /users/:id(.:format) profiles#destroy

And I am getting this error when trying to load the edit profile page (localhost:3000/settings/profile): "No route matches {:controller=>"devise/profiles", :action=>"destroy"}"

_form.html.haml

.row
  .span6
    .actions
      = f.submit 'Save', class: 'btn-submit'
      = link_to 'Delete Account', admin_destroy_user_path, method: :delete, data: { confirm: 'Are you sure?' }, class: 'btn-delete'
      = link_to 'Cancel', profile_index_path

profile_controller

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

  if @user.destroy
    redirect_to root_url, notice: "User deleted."
  end
end

routes.rb

devise_for :users    
match 'users/:id' => 'devise/registrations#destroy', :via => :delete, :as =>    :admin_destroy_user
match 'users/:id' => 'user#show', as: :user
resources :users

ability.rb

if user.is? :admin
  can :access, :admin #access the admin page
  can :manage, :all #do anything to any model
else
  can :read, :all #read any model
  can [:update, :destroy], Profile, :user_id => user.id

Solution

  • In your ProfileController you destroyed wrong object. The target should be profile, but not user.

    So it should be something like this

    def destroy
      @profile = Profile.find(user_id: params[:id])
      if @profile.destroy
        redirect_to root_url, notice: "User deleted."
      else
        render_error_message
      end
    end
    

    However, I really can't find any points to delete a profile. If the profile is empty, just show it as empty as what StackOverflow shows, which is normal.