自定义404页面 Rails

4

我是 Ruby 的初学者,不知道如何在 Rails 5 中创建自定义的404/401页面。有什么建议吗? 我已经创建了一个名为 "ErrorPages" 的控制器,并添加了一个 "page_404" 动作。 请帮帮我。

1个回答

4

试试这个:

class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordNotFound, with: :on_record_not_found
  rescue_from AbstractController::ActionNotFound, with: :on_record_not_found
  rescue_from ActionController::RoutingError, with: :on_routing_error
  rescue_from CanCan::AccessDenied, with: :on_access_denied

  def render_404
    if params[:format].present? && params[:format] != 'html'
      head status: 404
    else
      render 'application/404', status: 404
    end
  end

  def on_access_denied
    if params[:format].present? && params[:format] != 'html'
      head status: 401
    else
      render 'application/401', status: 401
    end
  end

  def on_record_not_found
    render_404
  end

  def on_routing_error
    render_404
  end
end

routes.rb

Rails.application.routes.draw do
  get '*unmatched_route', :to => 'application#render_404'
end

/app/views/application/404.html.slim

.content
 .row
  .col-md-12
    h1 404

不到一分钟?...看起来你把代码直接粘贴过来了,就这样... - Deepak Mahakale
1
你是否拥有这两个账户? - Deepak Mahakale
1
我只是把这些问题保存在https://www.evernote.com中,例如https://www.evernote.com/shard/s554/sh/5b04e531-758c-45b6-8f28-1a9a53fd3e6c/97bd855e98482cd808a5ba7ea46fd2e5。 - Serhii Danovskyi
301重定向 https://www.evernote.com/shard/s554/sh/e3633d93-2e5c-4ef9-8d2c-89b7ad442766/23e9770a5ef2e4f3ea00129da78368b7 - Serhii Danovskyi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接