Mongo ID导致可怕的URL [英] Mongo ids leads to scary URLs

查看:77
本文介绍了Mongo ID导致可怕的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来像是一个琐碎的问题,但这对于面向消费者的应用程序而言非常重要

This might sound like a trivial question, but it is rather important for consumer facing apps

将可怕的mongo id映射到友好的id上最简单,最可扩展的方法是什么?

What is the easiest way and most scalable way to map the scary mongo id onto a id that is friendly?

xx.com/posts/4d371056183b5e09b20001f9

xx.com/posts/4d371056183b5e09b20001f9

TO

xx.com/posts/a

xx.com/posts/a

M

推荐答案

在您的集合中定义一个友好的唯一字段(如slug),在模型上对其进行索引,然后定义to_param以返回它:

Define a friendly unique field (like a slug) on your collection, index it, on your model, define to_param to return it:

def to_param
  slug
end

然后在您的查找器中,按段标题而不是ID进行查找:

Then in your finders, find by slug rather than ID:

@post = Post.where(:slug => params[:id].to_s).first

这将使您将作为有效的PK来进行资源交互,并且它们更漂亮.

This will let you treat slugs as your effective PK for the purposes of resource interaction, and they're a lot prettier.

这篇关于Mongo ID导致可怕的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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