How can I use friendly ID in Rails like mysite.com/[USERNAME]

一曲冷凌霜 提交于 2019-12-04 07:25:25

I already ask this question on Quora..

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

For who really interested to implement Quora/Facebook URLs like. Heres a tip in Rails3:

Make a table called slugs :

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

Now in routes.rb add this line to the bottom:

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

so, if we go to /one in the routes, it translated to be:

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

Now in the show action in all controllers

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

You can use a gem called SubDomain-Fu for this. Watch this screen cast for more details.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!