ruby 呈现一个404页面,关于Rails中的路由错误

3wabscal  于 12个月前  发布在  Ruby
关注(0)|答案(3)|浏览(91)

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

kxe2p93d

kxe2p93d1#

而不是
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:

config.consider_all_requests_local       = false

**提示:**这也意味着你不会看到任何错误在你的应用程序上(stacktrace等视图)。

p1iqtdky

p1iqtdky2#

你需要把not_found放在ApplicationController中,而不是放在PostsController中,然后你不需要渲染它,你可以像这样调用它。

# your code above...
else
  not_found
end
cotxawn7

cotxawn73#

如果你想让一个页面显示没有页面存在的消息,那么只需要在Config -> environment _> development.rb文件中设置config.consider_all_requests_local = false。然后重新启动服务器,它将被修复。

相关问题