【问题标题】:How to show 404 page in Rails 4 without redirect?如何在没有重定向的 Rails 4 中显示 404 页面?
【发布时间】:2018-03-02 05:50:58
【问题描述】:

这是我目前处理错误的植入:

#routes.rb
match "/404", :to => "errors#not_found", :via => :all, as: 'not_found'
match "/500", :to => "errors#internal_server_error", :via => :all

#ErrorsController.rb
class ErrorsController < ApplicationController
  def not_found
    render(:status => 404)
  end

  def internal_server_error
    render(:status => 500)
  end
end

#views/errors/not_found.html.erb
(static HTML page)

我的问题是当我在我的网站中输入错误的 URL(例如 www.example.com/asdfasdf)时,我会被重定向到 www.example.com/404。作为比较,如果我访问 www.stackoverflow.com/asdfasdf,我会收到“找不到页面”错误,但 URL 仍然显示 www.stackoverflow.com/asdfasdf。

我想更改行为,使其与 Stack Overflow 中的工作方式相匹配,在这里我看到的是 404 页面,但 URL 与我输入的一样。最好的方法是什么?谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 routes url-routing


    【解决方案1】:

    试试这个:

    # routes.rb
    match "/404", :to => "errors#not_found", :via => :all, as: 'not_found'
    match "/500", :to => "errors#internal_server_error", :via => :all
    
    # errors_controller.rb
    class ErrorsController < ApplicationController
      def not_found
        render :file => 'public/404.html', :status => :not_found, :layout => false
      end
    
      def internal_server_error
        render :file => 'public/500.html', :status => :not_found, :layout => false
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2010-11-24
      • 1970-01-01
      • 2011-09-05
      • 2013-12-01
      • 1970-01-01
      • 2013-06-18
      • 2015-10-13
      • 2015-08-03
      • 1970-01-01
      相关资源
      最近更新 更多