如何从rails控制器动作发出404响应?

Rea*_*nly 41 ruby-on-rails

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

Jas*_*yon 36

这看起来不错......

# 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
Run Code Online (Sandbox Code Playgroud)

  • [这个答案](http://stackoverflow.com/questions/2385799/how-to-redirect-to-a-404-in-rails#answer-4983354)在另一个问题上让我觉得更强大.奖励:它包括测试代码:-) (6认同)
  • 在更高版本的rails中使用Rails.root.to_s而不是RAILS_ROOT (2认同)

mir*_*rza 33

你也可以

raise ActiveRecord::RecordNotFound

例外.

  • 例如使用`.find_by!`或`.first!` (2认同)

Nic*_*nko 28

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

raise ActionController::RoutingError.new('Not Found')
Run Code Online (Sandbox Code Playgroud)

要不就

raise ActionController::RoutingError, 'Not Found'
Run Code Online (Sandbox Code Playgroud)

或者还有其他一些解决方案: 如何在Rails中重定向到404?

  • 同样但更简单:`raise ActionController :: RoutingError,'Not Found'` (2认同)

tva*_*son 6

参考:

render :file => '/path/to/some/filenotfound.rhtml', 
                status => 404, :layout => true
Run Code Online (Sandbox Code Playgroud)


hua*_*lee 6

在ApplicationController中定义一个方法,如:

def render_404
  render :file => "#{RAILS_ROOT}/public/404.html",  :status => 404
end
Run Code Online (Sandbox Code Playgroud)


sen*_*nya 6

在 Rails 5 中你可以使用

head 404
Run Code Online (Sandbox Code Playgroud)

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