how to handle ActiveRecord::RecordNotFound in rails controller?

前端 未结 3 1542
闹比i
闹比i 2021-02-04 04:37

I have an app with user and events. Each user has several events. When a user wants to see a specific event he will get to this action:

def show
  begin
    @use         


        
3条回答
  •  耶瑟儿~
    2021-02-04 05:04

    Calling redirect_to doesn't return from your action method which is why moving on to the respond_to block causes the DoubleRenderError. One way to fix that is with:

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

    However, a better solution might be to either rescue from this exception declaratively or just let it propagate to the client. The former look like this:

    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
    

    If you just let the exception fester the user will see the public/404.html page in production mode.

提交回复
热议问题