2015-10-24 153 views
4

我第一次使用Devise gem來驗證用戶身份。我可以註冊,註銷,登錄和編輯用戶帳戶而沒有問題,但刪除帳戶不起作用!當我點擊按鈕進行刪除時,JS確認彈出,詢問我是否要刪除,點擊yes ...,然後我被重定向到用戶的顯示頁面。用戶帳戶完好無損。Rails&Devise:用戶帳戶沒有刪除

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> 

在我UsersController:

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

    if @user.destroy 
     redirect_to root_path 
    end 
end 

我還是on Rails的路由搖搖欲墜,但在我的routes.rb我:

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

以及:

resources :users 

當我運行rake航線,兩條航線,我認爲可以關聯是:

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

我敢肯定,我在做什麼錯誤的路線,但我看不到什麼。任何建議表示讚賞!

回答

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

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

資源

您遇到的問題是您沒有撥打delete HTTP verb;相反,你稱它爲destroymethod: :destroy)。

爲了給出上下文,HTTP協議由一系列verbs填充,以幫助您爲特定資源(url)定義不同的「操作」。這裏的Wikipedia的解釋:

HTTP定義了方法(有時也被稱爲動詞),以指示所希望的動作來識別的資源上執行。此資源代表的是預先存在的數據還是動態生成的數據,取決於服務器的實現。

因此,當您在routes of your app使用resources幫手,你會看到這路線產生:

enter image description here

正如上面可以看出,每次的聲明路線時間特別是resource,Rails自動填充了幾個預定義的URL /路徑。爲了讓您的應用正確處理您的請求,您必須將其發送到所請求的網址 - 並且該網址必須有效。

+0

謝謝!這工作。把我的動詞和動作搞混了! –

1

變化

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

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

您應該使用method: :deletemethod: :destroy

+0

謝謝!我把我的動詞和動作搞混了! –