简体   繁体   English

在 Rails 中,如何像 AngelList 那样为任意字符串生成路由?

[英]In Rails, how to generate routes for arbitrary string like AngelList does?

I'm trying to figure out how to generate the same routes as AngelList uses.我试图弄清楚如何生成与 AngelList 使用的相同的路线。 If you take a look at their URLs, you'll see they are of the following forms:如果您查看它们的 URL,您会发现它们属于以下 forms:

  • angel.co/ < username> angel.co/ <用户名>
  • angel.co/ < tag> angel.co/ <标签>
  • angle.co/ < link to internal page> angle.co/ <链接到内部页面>

How would you do this in Rails 3?你会如何在 Rails 3 中做到这一点?

Here's how I would do this (may not be the most efficient, but will work)这是我将如何做到这一点(可能不是最有效的,但会工作)

Create a dummy controller named URLRouter创建一个名为 URLRouter 的虚拟 controller

in config/routes.rb在 config/routes.rb

match ':object' => 'URLRouter#show'

This will call the SHOW action in your URLRouter controller, and place the thing they're requesting into params[:object].这将在您的 URLRouter controller 中调用 SHOW 操作,并将他们请求的内容放入 params[:object] 中。

In that URLRouter controller, place the following code:在该 URLRouter controller 中,放置以下代码:

if User.find_by_username(params[:object])
    render "users/show/#{params[:object]}"
end

Repeat this if statement for each of the different models.对每个不同的模型重复此 if 语句。 The first model will take precedence over the second model which will take precedence over the third model, etc.第一个 model 将优先于第二个 model,后者将优先于第三个 model 等。

Note that you need to ensure that you can't create a tag with the same value as a username, and you can't create a username equal to the same value as an internal link, and so on.请注意,您需要确保您不能创建与用户名具有相同值的标签,并且您不能创建与内部链接具有相同值的用户名,等等。 Otherwise you may end up with an inaccessible page (bc the URL will may route to a different model than you intended).否则,您可能会得到一个无法访问的页面(bc URL 可能会路由到与您预期不同的 model)。

Another important note is that if you modify your routes in this way, I would put this match statement after the rest.另一个重要的注意事项是,如果您以这种方式修改路由,我会将这个匹配语句放在 rest 之后。

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

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