Mongo ids leads to scary URLs

前端 未结 4 1228
时光取名叫无心
时光取名叫无心 2020-12-24 01:52

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

4条回答
  •  时光说笑
    2020-12-24 02:16

    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.

提交回复
热议问题