2015-02-06 202 views
0

我有一個刪除功能的問題。我做了以下內容:刪除功能無法正常工作

設置路線:

resources :todos do 
member do 
    delete :destroy_all 
end 
end 

建立一個鏈接index.html.erb

<%= link_to "Delete last seven days", destroy_all_todo_path(@todos), class: 'btn btn-success', method: :delete %> 

而且在我的控制器定義了以下方法:

def destroy_all 
@todo = Todo.where("created_at <= ?", Time.now - 7.days).destroy_all 
if @todo.destroy 
flash[:notice] = "Your old todos are deled!" 
else 
flash[:error] = "There was an error!" 
end 

但是,當我嘗試運行它時,我得到了錯誤:未定義的方法`銷燬'爲[]:Array

關於這裏出了什麼問題的任何想法?

+0

試着想象在你已經運行'destroy_all'之後'if @ todo.destroy'的行爲。 '@ todo'有什麼價值?我認爲應該清楚的是,這裏的'if'陳述沒有意義。 – ptd 2015-02-06 15:27:49

回答

3

這條線:

@todo = Todo.where("created_at <= ?", Time.now - 7.days).destroy_all 

銷燬所有的模型和返回你的已刪除記錄的數組。然後您在該陣列上撥打destroy

一般情況下,你不需要檢查destroy_all是否成功,至少我從來沒有一次失敗過。只要做到:

def destroy_all 
    Todo.where("created_at <= ?", Time.now - 7.days).destroy_all 
    flash.now[:notice] = "Your old todos are deled!" 
end 

如果你還是喜歡有一個後備,加入救援聲明 - 摧毀絕不會回報你假的,它一定會成功或引發異常。

0

正如@ptd在評論中指出的那樣,您正在刪除對象,然後嘗試再次刪除它們。我想你的代碼改成這樣:

def destroy_all 
@todos = Todo.where("created_at <= ?", Time.now - 7.days) 
if @todos.destroy_all 
flash[:notice] = "Your old todos are deled!" 
else 
flash[:error] = "There was an error!" 
end 

儘管此代碼將工作,@ BroiSatse的答案是更好,因爲檢查if聲明對一個空數組不會完成任何有用的東西。