如何在不实际渲染网页的情况下渲染404?

时间:2018-04-09 15:56:05

标签: controller http-status-code-404 ruby-on-rails-5 ruby-on-rails-5.1

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

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

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

2 个答案:

答案 0 :(得分:1)

最简单的方法是:

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

答案 1 :(得分:0)

最简单的方法是使用状态代码404呈现public / 404,您有404页布局的任何特定布局:true 否则布局:false 。然后返回一个假值

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