2016-01-13 111 views
1

我試圖通過傳遞該記錄的id來刪除記錄。代碼如下所示:在刪除Rails中的記錄時找不到記錄錯誤

def destroy_catalogue_entry 
    @catalogue_entry = CatalogueEntry.find(params[:catalogue_entry_id]) 
    if @catalogue_entry.destroy 
     flash[:success] = 'Catalogue entry deleted successfully.' 
    else 
     flash[:error] = 'Failed...' 
    end 
    end 

我收到了一個有趣的錯誤。當我的函數destroy_catalogue_entry把它叫做表明:

Couldn't find CatalogueEntry with 'id'=16 

但我如果條件部發表評論,並呈現@catalogue_entry爲JSON,輸出打印成功。那麼怎麼可能?我犯了一些愚蠢的錯誤還是有邏輯的原因。請賜教。

+0

什麼是在此操作時在控制檯中生成的sql查詢? – Richlewis

+0

你可以在控制檯中執行這些操作,並在此輸出: –

回答

0

我認爲destroy方法正在返回一個對象。在ruby中,if語句以外的任何東西都將被視爲true。你可以放置摧毀方法,看看它的返回。

0

我相信你,

@catalogue_entry = CatalogueEntry.find(params[:catalogue_entry_id]) 

返回了錯誤,因爲它不能與ID 6發現CatalogueEntry,請確保您有CatalogueEntry與該ID。

+0

你是對的,問題是相同的,但方式不同。現在它解決了。我已經添加了相同的答案。 – Imran

2

解決!我所做的一切是這樣的:

def destroy_catalogue_entry 
    @catalogue_entry = CatalogueEntry.find(params[:catalogue_entry_id]) 
    if @catalogue_entry.destroy 
     flash[:success] = 'Catalogue entry deleted Successfully' 
     redirect_to action: :view_catalogue_entries, dc_id: @catalogue_entry.dc_id 
    else 
     flash[:success] = 'Failed...' 
    end 
    end 

當我看到控制檯,該紀錄是越來越成功刪除,但之後,有對同一記錄一個SELECT查詢,這就是爲什麼它被扔的錯誤未能進行使用'id'= 16查找CatalogueEntry。當我重定向它時,問題解決了。