我想在Rails中“伪造”一个404页面。在PHP中,我只会发送一个带有错误代码的报头:

header("HTTP/1.0 404 Not Found");

Rails如何做到这一点?


当前回答

HTTP 404状态

要返回404报头,只需使用render方法的:status选项。

def action
  # here the code

  render :status => 404
end

如果希望呈现标准404页面,可以在方法中提取该特性。

def render_404
  respond_to do |format|
    format.html { render :file => "#{Rails.root}/public/404", :layout => false, :status => :not_found }
    format.xml  { head :not_found }
    format.any  { head :not_found }
  end
end

把它称为你的行动

def action
  # here the code

  render_404
end

如果希望操作呈现错误页面并停止,只需使用return语句。

def action
  render_404 and return if params[:something].blank?

  # here the code that will never be executed
end

ActiveRecord和HTTP 404

还要记住,Rails挽救了一些ActiveRecord错误,例如ActiveRecord::RecordNotFound显示404错误页面。

这意味着您不需要自己拯救这个操作

def show
  user = User.find(params[:id])
end

用户。find在用户不存在时引发ActiveRecord::RecordNotFound。这是一个非常强大的功能。请看下面的代码

def show
  user = User.find_by_email(params[:email]) or raise("not found")
  # ...
end

您可以通过将检查委托给Rails来简化它。简单地使用bang版本。

def show
  user = User.find_by_email!(params[:email])
  # ...
end

其他回答

为了测试错误处理,你可以这样做:

feature ErrorHandling do
  before do
    Rails.application.config.consider_all_requests_local = false
    Rails.application.config.action_dispatch.show_exceptions = true
  end

  scenario 'renders not_found template' do
    visit '/blah'
    expect(page).to have_content "The page you were looking for doesn't exist."
  end
end

HTTP 404状态

要返回404报头,只需使用render方法的:status选项。

def action
  # here the code

  render :status => 404
end

如果希望呈现标准404页面,可以在方法中提取该特性。

def render_404
  respond_to do |format|
    format.html { render :file => "#{Rails.root}/public/404", :layout => false, :status => :not_found }
    format.xml  { head :not_found }
    format.any  { head :not_found }
  end
end

把它称为你的行动

def action
  # here the code

  render_404
end

如果希望操作呈现错误页面并停止,只需使用return语句。

def action
  render_404 and return if params[:something].blank?

  # here the code that will never be executed
end

ActiveRecord和HTTP 404

还要记住,Rails挽救了一些ActiveRecord错误,例如ActiveRecord::RecordNotFound显示404错误页面。

这意味着您不需要自己拯救这个操作

def show
  user = User.find(params[:id])
end

用户。find在用户不存在时引发ActiveRecord::RecordNotFound。这是一个非常强大的功能。请看下面的代码

def show
  user = User.find_by_email(params[:email]) or raise("not found")
  # ...
end

您可以通过将检查委托给Rails来简化它。简单地使用bang版本。

def show
  user = User.find_by_email!(params[:email])
  # ...
end
<%= render file: 'public/404', status: 404, formats: [:html] %>

只需将此添加到要呈现到404错误页面的页面,就完成了。

你也可以使用渲染文件:

render file: "#{Rails.root}/public/404.html", layout: false, status: 404

你可以选择是否使用该布局。

另一种选择是使用Exceptions来控制它:

raise ActiveRecord::RecordNotFound, "Record not found."

这些会帮助你……

应用程序控制器

class ApplicationController < ActionController::Base
  protect_from_forgery
  unless Rails.application.config.consider_all_requests_local             
    rescue_from ActionController::RoutingError, ActionController::UnknownController, ::AbstractController::ActionNotFound, ActiveRecord::RecordNotFound, with: lambda { |exception| render_error 404, exception }
  end

  private
    def render_error(status, exception)
      Rails.logger.error status.to_s + " " + exception.message.to_s
      Rails.logger.error exception.backtrace.join("\n") 
      respond_to do |format|
        format.html { render template: "errors/error_#{status}",status: status }
        format.all { render nothing: true, status: status }
      end
    end
end

错误的控制器

class ErrorsController < ApplicationController
  def error_404
    @not_found_path = params[:not_found]
  end
end

视图/错误/error_404.html.haml

.site
  .services-page 
    .error-template
      %h1
        Oops!
      %h2
        404 Not Found
      .error-details
        Sorry, an error has occured, Requested page not found!
        You tried to access '#{@not_found_path}', which is not a valid page.
      .error-actions
        %a.button_simple_orange.btn.btn-primary.btn-lg{href: root_path}
          %span.glyphicon.glyphicon-home
          Take Me Home