在 Rails 中渲染路由错误的 404 页面 [英] render a 404 page on routing error in rails

查看:54
本文介绍了在 Rails 中渲染路由错误的 404 页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 Rails 中的集成 404 页面作为例外呈现.我试过了,但仍然得到路由错误页面:

I'm trying to render the integrated 404 page in rails as an exception. I tried this but still getting the routing error page:

posts_controller.rb

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

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 %>

没有路由匹配 [GET] "/posts/15/destroy"

推荐答案

代替

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

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

If you want to display 404 error page in development environment then make sure that the following is set to false in development.rb file:

  config.consider_all_requests_local       = false 

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

WARNING: This also means that you would not see any errors raised on your application(stacktrace etc in view).

这篇关于在 Rails 中渲染路由错误的 404 页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆