如何在 Rails 中使用友好 ID,例如 mysite.com/[USERNAME] [英] How can I use friendly ID in Rails like mysite.com/[USERNAME]

查看:38
本文介绍了如何在 Rails 中使用友好 ID,例如 mysite.com/[USERNAME]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在我的 Rails 应用程序中使用友好的 URL?我只需要提供以下网址格式

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

mysite.com/company1mysite.com/user123mysite.com/user1234mysite.com/newton.garciamysite.com/company-name

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

有人可以帮忙吗?

推荐答案

我已经在 Quora 上问过这个问题了..

I already ask this question on Quora..

http://www.quora.com/How-does-Quora-rewrite-their-urls

对于真正有兴趣实施 Quora/Facebook URL 的人.这是 Rails3 中的一个技巧:

For who really interested to implement Quora/Facebook URLs like. Heres a tip in Rails3:

制作一个名为 slugs 的表格:

Make a table called slugs :

#  slug | model_id |  model
# ===========================
# simple data:
#  one  |    2222    |  post
#  two  |    1111    |  user
#  six   |    5432    |  comment

现在在 routes.rb 中将此行添加到底部:

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

所以,如果我们去路由中的/one,它会被翻译成:

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"

现在在所有控制器的 show 操作中

Now in the show action in all controllers

@something = Model.find_by_slug(params[:id])

这篇关于如何在 Rails 中使用友好 ID,例如 mysite.com/[USERNAME]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆