开发者

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

开发者 https://www.devze.com 2023-03-18 22:42 出处:网络
I\'m trying to figure out how to generate the same routes as AngelList uses.If you take a look at their U开发者_Go百科RLs, you\'ll see they are of the following forms:

I'm trying to figure out how to generate the same routes as AngelList uses. If you take a look at their U开发者_Go百科RLs, you'll see they are of the following forms:

  • angel.co/<username>
  • angel.co/<tag>
  • angle.co/<link to internal page>

How would you do this in Rails 3?


Here's how I would do this (may not be the most efficient, but will work)

Create a dummy controller named URLRouter

in 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].

In that URLRouter controller, place the following code:

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

Repeat this if statement for each of the different models. The first model will take precedence over the second model which will take precedence over the third model, etc.

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).

Another important note is that if you modify your routes in this way, I would put this match statement after the rest.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号