2011-09-26 30 views
1

我已經得到了以下聲明:如果單純沒有找到記錄語句的問題

@all_comments = Comment.find(@task.id) 

的問題是,如果沒有意見,它拋出錯誤未找到記錄。我怎麼能讓這個失敗默默無聞,所以它什麼都不會返回?

+2

@ task.comments應該回到你的評論列表,如果有任何其他空數組,則是否已正確設置關係。 –

回答

5

你正在嘗試做不能正常工作。

該行find(@task.id)將尋找與task具有相同id的註釋,這通常不是您建立關係的方式。

通常你將有一個任務和意見表,意見表將有一個名爲task_id列。如果是這樣的話,可以按如下方式寫你的模型:

class Task 
    has_many :comments 
end 

class Comment 
    belongs_to :task 
end 

,然後你可以簡單的寫:

@all_comments = @task.comments 
+0

我完全錯過了! – d11wtq

1

我不使用AR,但我相信只是:

@all_comments = Comment.find(:first, @task.id) 

將返回nil,如果沒有找到記錄,不像#find沒有任何修飾。

編輯|有一個快捷方式太:

@all_comments = Comment.first(@task.id) 
1

我認爲你的失敗是一個不同的你期望。查詢請求與ID @task.id(其爲Task的ID)的Comment

您的查詢應該這樣:

@all_comments = Comment.where(:task_id => @task.id) 

甚至更​​好

@task.comments 

這應該工作,如果你有相應的聲明你的關係,並允許一些更多的選擇(添加評論,.. )。

看一看的"Rails Guides",和那裏的"Active Record Query Interface"

0

軌道拋出RecordNotfound例外find電話。使用find_by來避免這種情況。

如果您正在試圖通過TASK_ID然後用戶得到任務列表中find_all_by方法:

# returns an empty array when no tasks are found 
@comments = Comment.find_all_by_task_id(@task.id) 

否則使用find_by

# returns nil when no task is found 
@comment = Comment.find_by_task_id(@task.id)