Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirect to 404 page when a user record does not exist?

e.g I have one model (User model). When user signsup for an account, there is an email sent to alert user that his/her account has been activated. In this case, if an admin deletes user record and then user clicks the link from the email to see his or her profile, it will show error. So, I want to check if a user record exists or not. if it does not exist, user should be redirected to 404 page.

I have tried the code below but it not working. this is the following example that i have tried

def show
  @user = User.find(params[:id]) or raise ActionController::RoutingError.new('Not Found')
end

So, is there a solution for this?

Thanks.

like image 708
Parinha Avatar asked Dec 06 '25 08:12

Parinha


2 Answers

It's quite simple, you just need to render rails default 404 page or your customized one..

In your application controller,

class ApplicationController < ActionController::Base
 # rest of your application controller code

 def content_not_found
   render file: "#{Rails.root}/public/404.html", layout: true, status: :not_found
 end
end

Then, call it from any controller you wish. In you case,

def show
  if (@user = User.find_by_id(params[:id]).present?
    # do your stuff
  else
    content_not_found
  end
end

I don't like exceptions, and I try to avoid them as much as possible ;)

like image 144
Md. Farhan Memon Avatar answered Dec 08 '25 21:12

Md. Farhan Memon


Try this code instead:

def show
  @user = User.find_by(id: params[:id])

  raise ActionController::RoutingError.new('Not Found') if @user.blank?
end
like image 36
Gerry Avatar answered Dec 08 '25 22:12

Gerry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!