Mongo ids leads to scary URLs

2019-02-01 10:43发布

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

4条回答
SAY GOODBYE
2楼-- · 2019-02-01 10:49

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.

查看更多
男人必须洒脱
3楼-- · 2019-02-01 10:57

You can create a composite key in mongoid to replace the default id using the key macro:

class Person
  include Mongoid::Document
  field :first_name
  field :last_name
  key :first_name, :last_name
end

person = Person.new(:first_name => "Syd", :last_name => "Vicious")
person.id # returns "syd-vicious"

If you don't like this way to do it, check this gem: https://github.com/hakanensari/mongoid-slug

查看更多
聊天终结者
4楼-- · 2019-02-01 11:10

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

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

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

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

查看更多
叼着烟拽天下
5楼-- · 2019-02-01 11:16

Unfortunately, the key macro has been removed from mongo. For custom ids, users must now override the _id field.

class Band
  include Mongoid::Document
  field :_id, type: String, default: ->{ name }
end
查看更多
登录 后发表回答