0

how to rescue if user access the wrong url and then app redirect automatic to valid url using before filter, example i have valid url like this :

http:://localhost:3000/stores/

if i access with wrong url in browser, example like this :

http://localhost:3000/test/

i want my rails app automatic redirect to valid url => http:://localhost:3000/stores/, if i'm try to access wrong url like above. How do that?

thanks before

tardjo
  • 1,594
  • 5
  • 22
  • 38

2 Answers2

0

The rule of thumb is to show 404 to your users when they enter wrong address. If you really need to redirect the users from undefined urls and you are sure thats your use case, you could use routes redirect call to do so:

Here is how: http://guides.rubyonrails.org/routing.html#redirection

and for your wildcard redirect it might look similar to this:

get '*path' => redirect('/') at the end of routes.rb

Again - I would recommend not doing this at all.

madsheep
  • 416
  • 4
  • 6
0

I like the clean rescue_from clause, one (or all) of those three should do the trick:

In your application_controller.rb

  rescue_from ActionController::RoutingError,       :with => :redirect_missing
  rescue_from ActionController::UnknownController,  :with => :redirect_missing
  rescue_from ActionController::UnknownAction,      :with => :redirect_missing

  def redirect_missing
    # do your thing, e.g.
    redirect_to root_path
  end

Hope that helps

Piotr Kruczek
  • 2,384
  • 11
  • 18
  • Doing that is a bad idea - rescuing errors should not be your control flow. Routes are there to handle the paths ;) – madsheep Feb 04 '14 at 15:39