代码之家  ›  专栏  ›  技术社区  ›  Joe Holloway

如何从Rails控制器操作发出404响应?

  •  40
  • Joe Holloway  · 技术社区  · 17 年前

    从Rails控制器操作发出404响应的首选方法是什么?

    7 回复  |  直到 8 年前
        1
  •  36
  •   Erwin Bolwidt    12 年前

    这看起来不错…

    # Rails 2 and below
    render :file => "#{RAILS_ROOT}/public/404.html",  :status => 404
    
    # Rails 3 and up
    render :file => "#{Rails.root}/public/404.html",  :status => 404
    
        2
  •  32
  •   mirza    15 年前

    你也可以

    raise ActiveRecord::RecordNotFound

    例外。

        3
  •  25
  •   Community Mohan Dere    9 年前

    以下方法对我来说是最好的:

    raise ActionController::RoutingError.new('Not Found')
    

    或者只是

    raise ActionController::RoutingError, 'Not Found'
    

    或者还有其他一些解决方案: How to redirect to a 404 in Rails?

        4
  •  6
  •   tvanfosson    17 年前

    Reference :

    render :file => '/path/to/some/filenotfound.rhtml', 
                    status => 404, :layout => true
    
        5
  •  6
  •   huacnlee    17 年前

    在ApplicationController中,定义如下方法:

    def render_404
      render :file => "#{RAILS_ROOT}/public/404.html",  :status => 404
    end
    
        6
  •  1
  •   senya Kaleb    8 年前

    在Rails 5中,您可以使用

    head 404
    

    这会将操作的响应代码设置为 404 . 如果您在这之后立即从您的操作方法返回,您的操作将响应 四百零四 没有真实的身体。这在开发API端点时可能很有用,但是对于最终用户HTTP请求,您可能更喜欢使用一些可见的主体来通知用户有关错误的信息。

        7
  •  0
  •   camzillajs101    8 年前

    如果您想在重定向时发出状态代码(例如302),可以将其放入 routes.rb :
    get "/somewhere", to: redirect("/somewhere_else", status: 302) .
    但是,这只适用于重定向,而不是直接向上加载页面。