fra*_*ess 2 ruby ruby-on-rails rails-routing ruby-on-rails-4
我试图在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
Run Code Online (Sandbox Code Playgroud)
application_controller.rb
def not_found
raise ActionController::RoutingError.new('Not Found')
end
Run Code Online (Sandbox Code Playgroud)
的routes.rb
Booklist::Application.routes.draw do
get "pages/faq"
get "pages/about"
devise_for :users
resources :posts
root 'posts#index'
end
Run Code Online (Sandbox Code Playgroud)
视图:
<% 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 %>
Run Code Online (Sandbox Code Playgroud)
No route matches [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
UPDATE
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
Run Code Online (Sandbox Code Playgroud)
更新2
如果要404在development环境中显示错误页面,请确保在development.rb文件中将以下内容设置为false :
config.consider_all_requests_local = false
Run Code Online (Sandbox Code Playgroud)
警告:这也意味着您不会在应用程序中看到任何错误(视图中的堆栈跟踪等).