Skip to content

Instantly share code, notes, and snippets.

@AhmedNadar
Last active November 30, 2023 00:43
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save AhmedNadar/b450fd65eda9c4afb8e04e28f1348af6 to your computer and use it in GitHub Desktop.
Save AhmedNadar/b450fd65eda9c4afb8e04e28f1348af6 to your computer and use it in GitHub Desktop.
How to redirect to a 404 in Rails?
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
def not_found
raise ActionController::RoutingError.new('Not Found')
rescue
render_404
end
def render_404
render file: "#{Rails.root}/public/404", status: :not_found
end
end
# app/controllers/posts_controller.rb
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def index
@post = Post.all
end
def show
end
def new
@post = Post.new
end
def edit
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
# very important to have `exists?`
# read more => http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-exists-3F
@post = Post.friendly.find(params[:id]) or not_found
end
end
@marmolleonardo
Copy link

AhmedNadar

The sentence does not work:
@post = Post.friendly.find(params[:id]) or not_found
change by:
@post = Post.friendly.find(params[:id]) rescue not_found

Regards

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment