2009-04-23 74 views

回答

35

这似乎不错...

# 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 
+6

[这个答案](http://stackoverflow.com/questions/2385799/how-to-redirect-to-a-404-in-rails#answer-4983354)在另一个问题让我觉得更强大。奖励:它包含测试代码:-) – webmat 2012-01-31 20:16:04

+2

在更高版本的rails中使用Rails.root.to_s代替RAILS_ROOT – deb 2012-06-15 18:35:22

+1

@deb它有什么不同?字符串插值将隐含地调用`to_s`。 – 2014-06-25 12:32:34

6

Reference

render :file => '/path/to/some/filenotfound.rhtml', 
       status => 404, :layout => true 
6

在ApplicationController中定义的方法等:

def render_404 
    render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 
end 
30

您还可以

raise ActiveRecord::RecordNotFound

异常。

23

下面的方法是最适合我:

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

或只是

raise ActionController::RoutingError, 'Not Found' 

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

0

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

相关问题