2016-05-14 41 views
0

我有一個用戶控制器,如果我想,如果找不到用戶並將其重定向到適當的頁面,我可以解救出錯。但我想只在某些路線上使用rescue_from方法,而不是所有路線。類似在特定路線上使用rescue_from的導軌

rescue_from ActiveRecord::RecordNotFound, with: :record_not_found, except: [:new, :edit]

因此,相當多的東西是有辦法做到這一點?幫助表示讚賞!

class UserController < ApplicationController 

    before_action :get_user 

    rescue_from ActiveRecord::RecordNotFound, with: :record_not_found 

    def show 
    end 

    def new 
    end 

    def create 
    end 

    def edit 
    end 

    def update 
    end 

    private 
    def get_user 
     User.find(params[:id]) 
    end 

    def record_not_found 
     redirect_to user_path, error: "Sorry, no user found." 
    end 
end 

回答

0

--update -

可能把它變成

private 

def problem 
    begin 
    @user = User.find(params[:id]) 
    rescue ActiveRecord::RecordNotFound 
    redirect_to user_path, error: "Sorry, no user found." 
    end 
end 

,並有before_action

before_action :problem, except: [:new, :edit] 

這個問題也可能有助於rescue from ActiveRecord::RecordNotFound in Rails

1

讓我們只需要它的時候調用回調開始:

before_action :get_user, only: [:show, :edit, :update, :destroy] 

但是查詢的記錄甚至沒有被分配給一個變量,因此它可以在以後使用。讓我們解決這個問題:

class UserController < ApplicationController 
    before_action :set_user, only: [:show, :edit, :update, :destroy] 

    # ... 

    private 

    def set_user 
     @user = User.find(params[:id]) 
    end 
end 

雖然我們可以用rescue_from ActiveRecord::RecordNotFound, with: :record_not_found - 我們甚至不知道它實際上已失敗用戶查詢!例如,它可能是ApplicationController中定義的某個其他回調函數。

此外,當無法找到資源時,應用程序應通過發送404 - NOT FOUND410 - GONE響應告訴客戶端。不會因重定向而發送指示資源已暫時移動的3xx響應代碼。

你可以在回調直接營救異常,而不是:

def set_user 
     begin 
     @user = User.find(params[:id]) 
     rescue ActiveRecord::RecordNotFound 
     @users = User.all 
     flash.now[:error] = "User not found" 
     # note that we render - not redirect! 
     render :index, status: 404 
     end 
    end 

雖然在大多數情況下,最好把它留到默認的處理器,而不是貽誤了您的應用程序的REST接口,並添加了一堆複雜。

0

解決方案A,使用定義這個的before_filter,像一個普通的父控制器:

class RescueNotRoundRecordController < ApplicationController 
    rescue_from ActiveRecord::RecordNotFound, with: :record_not_found 

    private 
    def record_not_found 
    redirect_to user_path, error: "Sorry, no user found." 
    end 
end 

class UserController < RescueNotRoundRecordController 
    before_action :get_user 
end 

解決方案B,使用模塊要做到這一點,我認爲這是更好的方式去:

module RescueNotRoundRecord 
    def self.included(mod) 
    mod.class_eval do 
     rescue_from ActiveRecord::RecordNotFound, with: :record_not_found 
    end 
    end 

    private 
    def record_not_found 
    redirect_to user_path, error: "Sorry, no user found." 
    end 
end 

class UserController < ApplicationController 
    include RescueNotRoundRecord 
end