Getting the 404 Not Found error page by default "Active Record :: RecordNotFound" when I have a custom page for this

I have custom error pages for status code 404 and 500, and it works fine when I put localhost: 3000 / something.html. But it does not work when I put localhost: 3000 / controller / element_of_a_model.

routes.rb:

if Rails.env.production? then
  unless Rails.application.config.consider_all_requests_local
    get '*not_found', to: 'errors#error_404'
    get '*internal_server_error', to: 'errors#error_500'
  end
else
  unless
    get '*not_found', to: 'errors#error_404'
    get '*internal_server_error', to: 'errors#error_500'
  end
end

ErrorsController:

def error_404
    render_error 404
end

def error_500
    render_error 500
end

private
   def render_error(status)
       respond_to do |format|
           format.html { render 'error_' + status.to_s() + '.html', :status => status, :layout => 'errors'}
           format.all { render :nothing => true, :status => status }
   end
end
+4
source share
1 answer

You should put this in the application controller:

rescue_from ActiveRecord::RecordNotFound do |exception|
  render_error 404
end


def render_error(status)
  respond_to do |format|
    format.html { render 'error_' + status.to_s() + '.html', :status => status, :layout => 'errors'}
    format.all { render :nothing => true, :status => status }
  end
end

In fact, your ErrorController will run along routes, but you have to add logic for exceptions.

+7
source

All Articles