如何在不实际呈现我的网页的情况下呈现 404?

How do I render a 404 without actually rendering my web page?

我想在我的 Rails 5.1 应用程序的特定条件下呈现默认 404 页面。我的控制器里有这个

  def index
    ...
    if worker
    ...
    else
      puts "page not found"
      render :status => 404
    end
  end

但是,即使满足条件(我的 404 分支被调用),Rails 仍在尝试呈现我的 index.htrml.erb 页面,这会导致其他错误,因为预期的模型属性不在那里。有没有一种方法可以在不呈现页面的情况下返回 404 状态代码?

最简单的方法是:

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

另一种方法是引发一个错误,该错误将被 rails

捕获为 404

错误包括:ActionController::RoutingErrorAbstractController::ActionNotFoundActiveRecord::RecordNotFound

有了方法not_found,需要的时候可以调用

def not_found
  raise ActionController::RoutingError.new('Not Found')
end

def index
  ...
  if worker
  ...
  else
    puts "page not found"
    not_found
  end
end

对于其他格式,您可以只使用 head :not_found

最简单的方法是使用状态代码 404 呈现 public/404,您有 404 页的任何特定布局 layout: true otherwise layout : 假。然后 return 一个错误值

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