例如在路由中我有这样的代码:
get "profile/:id" => 'profiles#show', as: :profile
root 'articles#index'
但我怎么能捕捉到这种 url 并重定向到主页:
我需要捕捉任何不存在的路线。为什么我需要这个?通过 SEO 规则。例如,现在如果我输入 url.com/?porn 或 url.com/profile?1&azaza
- 我将进入我输入这个难看的 url 的页面。但是我需要重定向到主页,这样任何“黑客”就不会在他们的资源上发布非法链接...
这是真的吗?
最佳答案
您需要处理两种不同的情况
- 一条错误的道路
- 错误的资源
对于第一种,您可以在路由末尾添加全局匹配规则。
match '*foo', to: 'articles#index'
然后你应该在你的 Controller 中处理丢失的资源。
例如
def show
begin
@article = Article.find(params[:id])
rescue
redirect_to root_url
end
end
当然,如果您有多个 Controller 并且需要在许多地方重复,您应该使用更通用的方法。也许在你的 ApplicationController
ActiveRecord::RecordNotFound
关于ruby-on-rails - 目录 : how to catch any route that didn't match route config and redirect to homepage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29321457/