简体   繁体   English

从Rails中的route.rb中重定向

[英]Redirect from within routes.rb in Rails

I'm creating a history of name changes for records in my database. 我正在为数据库中的记录创建名称更改历史记录。 So if someone changes the name of something they own, old URLS still work. 因此,如果有人更改了自己拥有的商品的名称,则旧的URL仍然有效。

I'm trying something like this: 我正在尝试这样的事情:

get '/:id', to: "services#show", as: 'show_service', constraints: lambda {|request|
  urls = ['a', 'b', 'c']
  if urls.include? params[:id]
    puts "Yep - this works."
    return redirect latest_url
  else
    # Nothing matches, this service doesn't exist.
    return false
  end
}

Two ways for this route to complete: 此路线可以通过两种方式完成:

  1. WORKING: It finds nothing and returns false so the route execution order continues down. 工作:它什么也没有找到并返回false,因此路由执行顺序继续下降。

  2. NOT WORKING: It finds something and redirect to the latest name in the route history. 不起作用:它找到了东西并重定向到路线历史中的最新名称。

That return redirect latest_url isn't redirecting at all - any suggestions? 该返回重定向Latest_url根本没有重定向-有什么建议吗?

Since the tests against each route stop on the first match, it's simpler to have two routes: 由于针对每条路线的测试均在第一场比赛中停止,因此拥有两条路线更为简单:

# legacy name support
get '/:id', to: redirect(latest_url), constraints: lambda { |request|
  urls = ['a', 'b', 'c']
  urls.include? request.params[:id]
}

# latest and greatest
get '/:id', to: "services#show", as: 'show_service'

PS: I'd also suggest this is complex enough to warrant it's own class that responds to matches? PS:我还建议这很复杂,足以保证它是自己的班级来响应matches? instead of the inline lambda, see http://guides.rubyonrails.org/routing.html#advanced-constraints 而不是内联lambda,请参见http://guides.rubyonrails.org/routing.html#advanced-constraints

PPS: depending on the complexity of your use-case, it's worth taking a look at the friendly_id gem and it's history module. PPS:根据用例的复杂性,值得一看的是friendly_id gem及其历史模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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