我正在尝试将 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/