Skip to content

Instantly share code, notes, and snippets.

@nunommc
Last active September 9, 2020 02:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nunommc/ee3c2596b1acbce50818 to your computer and use it in GitHub Desktop.
Save nunommc/ee3c2596b1acbce50818 to your computer and use it in GitHub Desktop.
Redirect to page 404 when a Model.find(params[:id]) raises ActiveRecord::RecordNotFound
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
add_flash_types :success, :error
# See:
# https://stackoverflow.com/questions/2385799/how-to-redirect-to-a-404-in-rails
def not_found
raise ActionController::RoutingError.new('Not Found')
rescue
render_404
end
def render_404
respond_to do |format|
format.html { render :file => "#{Rails.root}/public/404",
# :layout => false,
:status => :not_found }
format.xml { head :not_found }
format.any { head :not_found }
end
end
end
# app/controllers/templates_controller.rb
class TemplatesController < ApplicationController
before_action :set_template, only: [:show, :edit, :update, :destroy]
def index
@template = Template.all
end
def show
end
def new
@template = Template.new
end
def edit
end
private
# Use callbacks to share common setup or constraints between actions.
def set_template
# very important to have `find_by_id` instead of `find`
@template = Template.find_by_id(params[:id]) or not_found
end
end
@AhmedNadar
Copy link

It works well as you shared above. But not with Friendly_id gem.
After reading a bit over FinderMethods on Rails 5. I found using exists? method instead of find_by_id works well. Since the gem convert IDs to Slugs (kind of...).

I have created a Gist which reflect such situation.

Thanks, your code has helped me...

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