如何在rails中找不到404的页面?

tar*_*djo 14 exception-handling ruby-on-rails

如果用户在rails中添加了错误的URL,如何救援未找到的页面.如果网址无效,我希望在公共文件夹中显示404页面.怎么做?我正在浏览它但找不到解决方案.我尝试了很多方法来解决问题,但它们似乎没有起作用.我被困在这里,请帮忙.

reb*_*tte 25

Rails的解决方案4

routes.rb上:

get '*unmatched_route', to: 'application#not_found'
Run Code Online (Sandbox Code Playgroud)

application_controller.rb上:

def not_found
  # Your exception handling code here
end
Run Code Online (Sandbox Code Playgroud)


tar*_*djo 11

我找到了解决方案,看看这个=> http://techoctave.com/c7/posts/36-rails-3-0-rescue-from-routing-error-solution(伟大的解决方案)

routes.rb:

# at the end of you routes.rb
match '*a', :to => 'errors#routing', via: :get
Run Code Online (Sandbox Code Playgroud)

errors_controller.rb:

class ErrorsController < ApplicationController
  def routing
    render_404
  end
end
Run Code Online (Sandbox Code Playgroud)

application.rb:

rescue_from ActionController::RoutingError, :with => :render_404

 private
  def render_404(exception = nil)
    if exception
        logger.info "Rendering 404: #{exception.message}"
    end

    render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
  end
Run Code Online (Sandbox Code Playgroud)

  • 如果它可以处理其他mime类型的通用,那将是很好的.像non-exist.js或does-not-exists.xml (2认同)