2012-10-01 64 views
14

我有一個用戶和事件的應用程序。每個用戶有幾個事件。當用戶想看到一個特定的事件,他會得到這個動作:如何在rails控制器中處理ActiveRecord :: RecordNotFound?

def show 
    begin 
    @userEvents = current_user.event 
    @event = @userEvents.find(params[:id]) 
    rescue ActiveRecord::RecordNotFound 
    redirect_to :controller => "main", :action => "index" 
    end 

    respond_to do |format| 
    format.html # show.html.erb 
    format.json { render json: @event } 
    end 
end 

如果沒有發現因爲它意味着他扮演的URL,他正在試圖獲得不屬於該事件的用戶事件給他。我想將他重定向到主頁面,或者只顯示頁面,並顯示找不到該事件的錯誤。如果我嘗試運行上面這個錯誤火災代碼:

AbstractController::DoubleRenderError in EventsController#show 

什麼是解決這個問題的最好方法是什麼?

回答

20

認沽返回重定向

begin 
@userEvents = current_user.event 
@event = @userEvents.find(params[:id]) 
rescue ActiveRecord::RecordNotFound 
redirect_to :controller => "main", :action => "index" 
return 
end 
+0

哦,上帝感謝....從未來發送消息=) –

14

調用redirect_to不會這就是爲什麼在移動到respond_to塊導致DoubleRenderError動作方法返回後。要解決這個問題的方法之一是:

redirect_to :controller => "main", :action => "index" and return 

然而,一個更好的解決方案可能是要麼rescue from此異常聲明,還是讓它傳播到客戶端。前者是這樣的:

class YourController < ActionController::Base 

    rescue_from ActiveRecord::RecordNotFound, with: :dude_wheres_my_record 

    def show 
    # your original code without the begin and rescue 
    end 

    def dude_where_my_record 
    # special handling here 
    end 
end 

如果你讓異常潰爛的用戶將看到public/404.html頁的生產模式。

+0

沒有聲張了解您的解決方案......爲什麼要救援發生在控制器每一次?我需要它只是在展示行動。但是謝謝 –

+0

'rescue_from'只是處理常見錯誤的一種更好的方式,可以讓您分離代碼中的疑慮。當然,它並不總是更好,因此另外兩個選項:-) – noodl

+0

THANKs ....它也適用於我= = –

5

在應用控制器,請寫信至:

rescue_from (ActiveRecord::RecordNotFound) { |exception| handle_exception(exception, 404) } 

    protected 

    def handle_exception(ex, status) 
     render_error(ex, status) 
     logger.error ex 
    end 

    def render_error(ex, status) 
     @status_code = status 
     respond_to do |format| 
      format.html { render :template => "error", :status => status } 
      format.all { render :nothing => true, :status => status } 
     end 
    end 

創建一個頁面error.html.erb

<div class="page-header"> 
    <h1> 
    <%= t "errors.#{@status_code}.heading" %> 
    <small><%= t "errors.#{@status_code}.subheading" %></small> 
    </h1> 
</div> 
<p><%= t "errors.#{@status_code}.description" %></p> 
<% if defined? root_path %> 
    <%= link_to t(:return_to_home), root_path %> 
<% end %> 

和en.yml

en: 
    errors: 
    "404": 
     description: "The page you are looking for does not exist!" 
     heading: "Record not found" 
     subheading: "" 
+0

快速注意,error.htm.erb應該進入/ views文件夾根目錄。 –

相關問題