如何在Rails中使用友好ID,如mysite.com/

如何在我的Rails应用程序上使用友好URL? 我只需要提供以下url格式

mysite.com/company1 mysite.com/user123 mysite.com/user1234 mysite.com/newton.garcia mysite.com/company-name

有人可以帮忙吗?

我已经在Quora上问过这个问题了..

http://www.quora.com/How-does-Quora-rewrite-their-urls

对于真正有兴趣实施Quora / Facebook URL的人。 下面是Rails3中的一个提示:

制作一个名为slugs的表:

 # slug | model_id | model # =========================== # simple data: # one | 2222 | post # two | 1111 | user # six | 5432 | comment 

现在在routes.rb中将此行添加到底部:

 match '/:id', :to => proc { |env| id = env["action_dispatch.request.path_parameters"][:id] model = Slug.find_by_slug(id).model controller = [model.pluralize.camelize,"Controller"].join.constantize controller.action("show").call(env) }, :as => :slugable 

所以,如果我们去路线中的/one ,它翻译为:

 id: one so from the slugs table, model: post and the route will point to "posts#show" 

现在在所有控制器的show动作中

 @something = Model.find_by_slug(params[:id]) 

您可以使用名为SubDomain-Fu的gem。 观看此屏幕投射以获取更多详细信息