2009-04-23 73 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)
但是,這隻適用於重定向,而不是直接加載頁面。

相關問題