Last Updated: February 25, 2016
·
578
· Alexandr K

Generate unique_id module

It's quite simple unique id module for mongoid:

module UniqueId
  def unique_id(field)
    instance_eval %Q{
      before_validation do
        self.#{field} ||= SecureRandom.uuid
      end
    }
  end
end

Example:

class TestModel
  include Mongoid::Document


  field :test_id

  extend UniqueId
  unique_id :test_id
end