在rails中显示路由错误的404页面

时间:2014-03-30 19:25:48

标签: ruby-on-rails ruby ruby-on-rails-4 rails-routing

我尝试在rails中呈现集成的404页面作为例外。我试过这个但仍然得到路由错误页面:

posts_controller.rb

def destroy
if current_user.username == @post.email 
@post.destroy
respond_to do |format|
  format.html { redirect_to posts_url }
  format.json { head :no_content }
end
else
  not_found
end

application_controller.rb

 def not_found
  raise ActionController::RoutingError.new('Not Found')
end 

的routes.rb

 Booklist::Application.routes.draw do
 get "pages/faq"
 get "pages/about"
 devise_for :users
 resources :posts

 root 'posts#index'
 end

视图:

<% if current_user.username == post.email %>
  <font color="red">This is your post! Feel free to edit or delete it. ->  </font>
    <%= link_to 'Edit', edit_post_path(post) %>
    <%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %>
    <% end %>

No route matches [GET] "/posts/15/destroy"

2 个答案:

答案 0 :(得分:9)

而不是

render not_found

你可以使用

render file: "#{Rails.root}/public/404.html" , status: 404

或者

render file: "#{Rails.root}/public/404.html" , status: :not_found

<强>更新

def destroy
  if current_user.username == @post.email 
    @post.destroy
    respond_to do |format|
      format.html { redirect_to posts_url }
      format.json { head :no_content }
    end
  else
    render file: "#{Rails.root}/public/404.html" , status: :not_found
  end
end  ## end is missing

更新2

如果要在404环境中显示development错误页面,请确保在development.rb文件中将以下内容设置为false:

  config.consider_all_requests_local       = false 

警告:这也意味着您不会在应用程序中看到任何错误(视图中的堆栈跟踪等)。

答案 1 :(得分:1)

您需要将not_found放在ApplicationController中,而不是PostsController,然后您不需要渲染它,您可以将其称为

# your code above...
else
  not_found
end