- Code bellow shows how to redirect to 404 page, when your application use
friendly_id
gem. - Use
find
method instead offind_by_id
will work well and prevent of throwing errors.
Last active
November 30, 2023 00:43
-
-
Save AhmedNadar/b450fd65eda9c4afb8e04e28f1348af6 to your computer and use it in GitHub Desktop.
How to redirect to a 404 in Rails?
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 | |
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 |
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/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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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