如果用户使用rails中的redirect_to有效url访问错误的url rescue

时间:2014-01-28 09:24:01

标签: ruby-on-rails url before-filter

如果用户访问错误的网址,然后应用程序在过滤前使用自动重定向到有效网址,如何营救,例如我有这样的有效网址:

http:://localhost:3000/stores/

如果我在浏览器中使用错误的URL访问,例如:

http://localhost:3000/test/

我希望我的rails应用程序自动重定向到有效的url => http:://localhost:3000/stores/,如果我尝试访问上面错误的网址。怎么样?

之前感谢

2 个答案:

答案 0 :(得分:0)

经验法则是当用户输入错误的地址时向他们显示404。如果您确实需要将用户从未定义的URL重定向,并且您确定这是您的用例,则可以使用路由重定向调用来执行此操作:

以下是:http://guides.rubyonrails.org/routing.html#redirection

并且对于您的通配符重定向,它可能看起来类似于:

get '*path' => redirect('/') 在routes.rb的末尾

再次 - 我建议不要这样做。

答案 1 :(得分:0)

我喜欢干净的rescue_from条款,这三个中的一个(或全部)应该可以解决这个问题:

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

希望有所帮助