Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - any fancy ways to handle 404s?

I have a rails app I built for an old site I converted from another cms (in a non-rails language, hehe). Most of the old pages are mapped to the new pages using routes.rb. But there are still a few 404s.

I am a rails newb so I'm asking if there are any advanced ways to handle 404s. For example, if I was programming in my old language I'd do this:

  • Get the URL (script_name) that was being accessed and parse it.
  • Do a lookup in the database for any keywords, ids, etc found in the new URL.
  • If found, redirect to the page (or if multiple records are found, show them all on a results page and let user choose). With rails I'd probably want to do :status => :moved_permanently I'm guessing?
  • If not found, show a 404.

Are there any gems/plugins or tutorials you know of that would handle such a thing, if it's even possible. Or can you explain on a high level how that can be done? I don't need a full code sample, just a push in the right direction.

PS. It's a simple rails 3 app that uses a single Content model.

like image 686
jyoseph Avatar asked Jan 08 '11 22:01

jyoseph


1 Answers

Put this in routes (after every other route that you have, this will capture every url)

match '*url' => 'errors#routing'

And now in errors controller in routing action you can implement any fancy logic that you want, and render a view as always (you might want to add :status => 404 to the render call). Requested url will be available in controller as params[:url].

like image 72
Marek Sapota Avatar answered Sep 28 '22 20:09

Marek Sapota