Railsのルーティングエラーで404ページをレンダリングする
概要
例外として Rails に統合された 404 ページをレンダリングしようとしています。これを試してみましたが、依然としてルーティング エラー ページが表示されます。
post_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
アプリケーションコントローラー.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
開発環境で 404 エラー ページを表示したい場合は、development.rb ファイルで以下が false に設定されていることを確認してください。
config.consider_all_requests_local = false
警告: これは、アプリケーション (スタックトレースなどのビュー) で発生するエラーが表示されないことも意味します。