Last active
September 9, 2020 02:19
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 offind_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...