简体   繁体   中英

rails handling 404 on webrick getting ActiveRecord::RecordNotFound - simple questioon

So, I have a catch all route that is going to act like a vanity url piece. So, I have a call:

def show_profile
  url=VanityUrl.find_by_url!(params[:username])
  ...
end

I'm seeing somewhat different info for how I should be handling the ActiveRecord::NotFound error. I just want it to return a template in shared/404.html.erb

How would I do this?

As I understood, if record not found, we need to show /shared/404.html.erb.

def show_profile
  url = VanityUrl.find_by_url!(params[:username]) rescue nil
  unless url
    render "#{RAILS_ROOT}/shared/404.html.erb"
    return
  end
end

Should work. Reference: http://guides.rubyonrails.org/layouts_and_rendering.html

You can to use in the application controller

rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found

def record_not_found
   # logger, flash[:error], render, redirect, etc if RAILS_ENV == "production"
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM