【发布时间】:2010-03-12 03:07:55
【问题描述】:
如何在我的 Rails 应用程序中使用友好的 URL? 我只需要提供以下 url 格式
mysite.com/company1 mysite.com/user123 mysite.com/user1234 mysite.com/newton.garcia mysite.com/company-name
谁能帮忙?
【问题讨论】:
标签: ruby-on-rails seo friendly-id
如何在我的 Rails 应用程序中使用友好的 URL? 我只需要提供以下 url 格式
mysite.com/company1 mysite.com/user123 mysite.com/user1234 mysite.com/newton.garcia mysite.com/company-name
谁能帮忙?
【问题讨论】:
标签: ruby-on-rails seo friendly-id
我已经在 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。观看此screen cast 了解更多详情。
【讨论】: