General rescue throughout controller when id not found - RoR

后端 未结 4 1985
野的像风
野的像风 2021-02-07 11:21

I have stumbled upon a situation where my application looks for an id that does not exist in the database. An exception is thrown. Of course, this is a pretty standard situation

4条回答
  •  自闭症患者
    2021-02-07 12:08

    If you're talking about doing this within a single controller (as opposed to doing this globally in every controller) then here are a couple options:

    You can use a before_filter to setup your resource:

    class CustomerController < ApplicationController
      before_filter :get_customer, :only => [ :show, :update, :delete ]
    
      def show
      end
    
      private
    
      def get_customer
        @customer = ActiveRecord.find(params[:id])
        rescue ActiveRecord::RecordNotFound
          redirect_to :action => :index
      end
    end
    

    Or you might use a method instead. I've been moving in this direction rather than using instance variables inside views, and it would also help you solve your problem:

    class CustomerController < ApplicationController
      def show
        # Uses customer instead of @customer
      end
    
      private
    
      def customer
        @customer ||= Customer.find(params[:id])
        rescue ActiveRecord::RecordNotFound
          redirect_to :action => :index
      end
      helper_method :customer
    end
    

提交回复
热议问题