Mongo ids 导致可怕的 URL
这听起来可能是一个微不足道的问题,但对于面向消费者的应用程序来说相当重要
将可怕的 mongo id 映射到友好的 id 的最简单方法和最具可扩展性的方法是什么?
xx.com/posts/4d371056183b5e09b20001f9
致
xx.com/posts/a
M
This might sound like a trivial question, but it is rather important for consumer facing apps
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
TO
xx.com/posts/a
M
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在 mongoid 中创建一个复合键,以使用键宏替换默认 id:
如果您不喜欢这种方式,请检查此 gem: https://github.com/hakanensari/mongoid-slug
You can create a composite key in mongoid to replace the default id using the key macro:
If you don't like this way to do it, check this gem: https://github.com/hakanensari/mongoid-slug
在您的集合上定义一个友好的唯一字段(如 slug),对其进行索引,在您的模型上定义
to_param
以返回它:然后在您的查找器中,通过 slug 而不是 ID 进行查找:
这将让您为了资源交互的目的,将蛞蝓视为你的有效PK,而且它们更漂亮。
Define a friendly unique field (like a slug) on your collection, index it, on your model, define
to_param
to return it:Then in your finders, find by slug rather than ID:
This will let you treat slugs as your effective PK for the purposes of resource interaction, and they're a lot prettier.
不幸的是,关键的宏已从 mongo 中删除。对于自定义 ID,
用户现在必须覆盖 _id 字段。
Unfortunately, the key macro has been removed from mongo. For custom ids,
users must now override the _id field.
这是我用来成功解决这个问题的一个很棒的宝石:Mongoid-Slug
https://github。 com/digitalplaywright/mongoid-slug。
它提供了一个很好的界面来跨多个模型添加此功能。如果您想自己动手,至少检查一下他们的实现以获取一些想法。如果您要走这条路,请查看 Stringex gem,https://github.com/rsl/stringex 和acts_as_url 库内。这将帮助您获得漂亮的 url 之间的破折号。
Here's a great gem that I've been using to successfully answer this problem: Mongoid-Slug
https://github.com/digitalplaywright/mongoid-slug.
It provides a nice interface for adding this feature across multiple models. If you'd rather roll your own, at least check out their implementation for some ideas. If you're going this route, look into the Stringex gem, https://github.com/rsl/stringex, and acts_as_url library within. That will help you get the nice dash-between-url slugs.