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/compan开发者_JAVA技巧y-name
Can anyone help ?
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.
精彩评论