我正尝试将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"
3条答案
按热度按时间kxe2p93d1#
而不是
render not_found
你可以用
render file: "#{Rails.root}/public/404.html" , status: 404
或
render file: "#{Rails.root}/public/404.html" , status: :not_found
更新
更新2
如果您想在
development
环境中显示404
错误页面,请确保在development.rb
文件中将以下内容设置为false:**提示:**这也意味着你不会看到任何错误在你的应用程序上(stacktrace等视图)。
p1iqtdky2#
你需要把
not_found
放在ApplicationController
中,而不是放在PostsController
中,然后你不需要渲染它,你可以像这样调用它。cotxawn73#
如果你想让一个页面显示没有页面存在的消息,那么只需要在Config -> environment _> development.rb文件中设置config.consider_all_requests_local = false。然后重新启动服务器,它将被修复。