0

我有我的文件控制器的刪除操作的一個奇怪的情況。'刪除'動作發生兩次?

Started GET "/files/35/delete" for 127.0.0.1 at 2011-02-27 01:13:51 -0500 
Processing by FilesController#delete as HTML 
Parameters: {"id"=>"35"} 
SQL (0.3ms) DELETE FROM `files` WHERE (`files`.`id` = 35) 
SQL (0.7ms) COMMIT 
Redirected to http://localhost:3000/files 
Completed 302 Found in 713ms 

Started GET "/files/35/delete" for 127.0.0.1 at 2011-02-27 01:13:52 -0500 
Processing by FilesController#delete as HTML 
Parameters: {"id"=>"35"} 
...leads to error 

控制器動作:

@file = @company.files.where("id = ?", params[:id]).first 
@file.destroy 
flash[:notice] = "Your file was deleted successfully." 
redirect_to files_url 

路線:

resources :files do 
    member do 
    get 'delete_ask' 
    get 'delete' 
    end 
end 

你知道爲什麼發生這種情況?

回答

0
@file = @company.files.where("id = ?", params[:id]).first 
if @file 
    @file.destroy 
    flash[:notice] = "Your file was deleted successfully." 
else 
    #file was deleted 
    flash[:notice] = "Patience: you only need to press delete once" 
end 
redirect_to files_url 

你可以從rescue錯誤:

@file = @company.files.where("id = ?", params[:id]).first 
    @file.destroy 
    flash[:notice] = "Your file was deleted successfully. 
#rescue from error 
rescue 
    flash[:notice] = "Patience: you only need to press delete once" 
    redirect_to files_url 
2

我懷疑這是由於雙重提交請求而發生的。儘量避免double在客戶端通過javascript或在服務器端提交(這將需要比客戶端更多的努力,但更強大)。