2015-09-01 33 views
8

處理錯誤然後找不到ID的最佳方法是什麼? 我有這樣的代碼在我的控制器:如何在找不到ID時處理錯誤?

def show 
    @match = Match.find(params[:id]) 
    end 

我在想是這樣的:

def show 
    if @match = Match.find(params[:id]) 
    else 
     render 'error' 
    end 
    end 

但我仍然得到:

的ActiveRecord :: RecordNotFound在MatchesController#秀

找不到'id'= 2的匹配

爲什麼?

什麼是正確的解決方案?

+1

'@match = Match.find_by_id(PARAMS [:編號])'如果記錄不存在@match將舉行'nil' – Nithin

回答

20

拯救它基礎控制器,並儘可能簡化您的操作代碼。 你不想在每個動作中都發現異常,你呢?

class ApplicationController < ActionController::Base 
    rescue_from ActiveRecord::RecordNotFound, :with => :render_404 

    def render_404 
    render :template => "errors/error_404", :status => 404 
    end 
end 
+5

+1。並且請用甜美可愛的貓咪做一個自定義的404頁面,做一些隨機的東西,同時說404.大家都喜歡那個! –

4

默認情況下,find方法會產生ActiveRecord::RecordNotFound異常。處理未找到記錄正確的方法是:

def show 
    @match = Match.find(params[:id]) 
rescue ActiveRecord::RecordNotFound => e 
    render 'error' 
end 

但是,如果您喜歡的if/else方法,您可以使用find_by_id方法將返回nil:

def show 
    @match = Match.find_by_id(params[:id]) 
    if @match.nil?  # or unless @match 
    render 'error' 
    end 
end 
+0

除非@match = Match.find_by(id:params [:id]) render'error' end #is做同樣的事情,並保存一行代碼:P –

+2

當然,但我非常喜歡可讀代碼來短代碼:D –

+1

render:錯誤,除非@匹配#應該是最適合你的:P –

1

您可以使用find_by_id方法則返回nil而不是拋出異常

Model.find_by_id 
0

有兩種方法丟失:

一種方法是使用一個空值對象(有我離開研究了給你)

其他人被提及,但可以放置更多的可重用和更優雅的方式(但它是有點隱藏你的行動代碼,因爲它 工作在略高的水平,隱藏的東西):

class MyScope::MatchController < ApplicationController 
    before_action :set_match, only: [:show] 

    def show 
    # will only render if params[:id] is there and resolves 
    # to a match that will then be available in @match. 
    end 

    private 

    def set_match 
    @match = Match.find_by(id: params[:id]) 
    if [email protected]? 
     # Handle somehow, i.e. with a redirect 
     redirect_to :back, alert: t('.match_not_found') 
    end 
    end 
end 
相關問題