- 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.
-
-
Save AlekseyPn/ae8f3bd01afb8eb132af598ddcaebd51 to your computer and use it in GitHub Desktop.
How to redirect to a 404 in Rails?
This file contains 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 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