2010-04-11 38 views
2

用戶可以使用URL在我的webapp中查看特定條目。例如,/entry/8。如果條目不存在,則「找不到條目」會附加到@messages,並且會顯示一個錯誤頁面。露營:將用戶返回到最近的條目,但保持錯誤

我想顯示一些任意查詢而不是空白頁面,但我找不到一個好方法來保持顯示錯誤消息。在任意查詢的控制器中還有其他操作需要進行,因此我不能僅複製查詢和render :posts

一些示例代碼:

 
module MyApp::Controllers 
    class ComplexQuery < R '/query' 
    def get 
     @entries = Entries.all(:conditions => someComplexConditions) 
     until @entries.complexEnough? then @entries.makeMoreComplex! end 
    end 
    end 

    class SingleEntry < R '/entry/(\d+)' 
    def get(id) 
     @entries = Entries.find_all_by_id(id) 
     unless @entries.nil? 
     render :posts 
     else 
     @messages = ["That entry does not exist."] 
     render :blank # I want to run Controllers::ComplexQuery, instead of rendering a blank page. 
     end 
    end 
    end 
end 

回答

3

像這樣的事情?

def get(id) 
    @entries = Entries.find_all_by_id(id) 
    unless @entries.nil? 
    render :posts 
    else 
    r *MyApp.get(:ComplexQuery) 
    end 
end 

請參閱Camping.method_missing

不過我也建議移動ComplexQuery成一個輔助方法:

module MyApp::Helpers 
    def complex_query(conditions); end 
end 

然後你可以在complex_query(something)既SingleEntry和ComplexQuery。

0

試試這個:

@entry = Entry.find_by_id(params[:id]) # returns nil when not found 
if @entry.nil? 
    flash[:notice] = "Entry not found" 
    render :action => "recent" 
end 
+0

我不想重複查詢。對於最近的帖子,這是一件簡單的事情,但是重複所有處理以重複潛在的複雜用戶輸入查詢對於每個可能具有驗證失敗的控制器來說都是很多工作。 – harbichidian 2010-04-13 22:28:52

+0

查詢條件不會是用戶輸入的,但我希望你明白了。 – harbichidian 2010-04-13 22:43:32

相關問題