how to handle ActiveRecord::RecordNotFound in rails controller?

前端 未结 3 1496
闹比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:02

    In application controller, please write:

        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
    

    Create a page error.html.erb

    
    

    <%= t "errors.#{@status_code}.description" %>

    <% if defined? root_path %> <%= link_to t(:return_to_home), root_path %> <% end %>

    and in en.yml

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

提交回复
热议问题