【问题标题】:How can I use friendly ID in Rails like mysite.com/[USERNAME]如何在 Rails 中使用友好 ID,例如 mysite.com/[USERNAME]
【发布时间】: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


    【解决方案1】:

    我已经在 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])
    

    【讨论】:

      【解决方案2】:

      您可以为此使用名为 SubDomain-Fu 的 gem。观看此screen cast 了解更多详情。

      【讨论】:

      • 这是最好的方法吗?我想要的是提供像 Facebook 这样的用户唯一 URL。 facebook.com/newtongarcia facebook.com/username1 facebook.com/username2
      • 我的答案中链接的屏幕截图与您的用例相似。观看以了解更多详情。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      相关资源
      最近更新 更多