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

半世苍凉 提交于 2019-12-06 02:44:21

问题


How can I use friendly URLs on my Rails application ? All I need is to make available the following url format

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

Can anyone help ?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/2430265/how-can-i-use-friendly-id-in-rails-like-mysite-com-username

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