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.
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 ;)
Try this code instead:
def show
@user = User.find_by(id: params[:id])
raise ActionController::RoutingError.new('Not Found') if @user.blank?
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With