Mongo ids leads to scary URLs

前端 未结 4 1229
时光取名叫无心
时光取名叫无心 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:07

    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
    
    0 讨论(0)
  • 2020-12-24 02:15

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 02:33

    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

    0 讨论(0)
提交回复
热议问题