ruby-on-rails - 在 Rails 中呈现路由错误的 404 页面

标签 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

应用程序 Controller .rb

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

路线.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"

最佳答案

代替

渲染 not_found

你可以用

呈现文件:“#{Rails.root}/public/404.html”,状态:404

或者

呈现文件:“#{Rails.root}/public/404.html”,状态::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 :

  config.consider_all_requests_local       = false 

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

关于ruby-on-rails - 在 Rails 中呈现路由错误的 404 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22748697/

相关文章:

ruby-on-rails - ruby ;加载它的进程类型

ruby - 我如何分析 1.9.2 中的 Ruby 代码?

ruby-on-rails - 检查具有特定参数的重新请求作业是否在队列中挂起

ruby-on-rails - RAILS 查询 - 如何使用 'where' 方法 - rails 4

mysql - Rails 4/RSpec - 测试 Controller 规范中保存到 MYSQL 数据库的时间值

ruby-on-rails - 如何将 Rails DateTime 分辨率限制为微秒?

ruby-on-rails - 如何为测试目的模拟数据库故障(在 Ruby on Rails 中)

ruby-on-rails - 如何检查值是否为数字?

ruby-on-rails - 按 Rails 中的嵌套关​​联进行分组和计数

ruby - 如何计算 Ruby 中两个普通区间的交集?