如何在我的 Rails 应用程序中使用友好的 URL?我只需要提供以下 url 格式
mysite.com/company1 mysite.com/user123 mysite.com/user1234 mysite.com/newton.garcia mysite.com/company-name
任何人都可以帮忙吗?
如何在我的 Rails 应用程序中使用友好的 URL?我只需要提供以下 url 格式
mysite.com/company1 mysite.com/user123 mysite.com/user1234 mysite.com/newton.garcia mysite.com/company-name
任何人都可以帮忙吗?
我已经在知乎上问过这个问题了。。
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 。观看此屏幕截图以了解更多详细信息。