Mongo ids leads to scary URLs

2019-02-01 10:14发布

问题:

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

回答1:

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.



回答2:

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



回答3:

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


回答4:

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.