Search code examples
mongoidcompositevalidates-uniqueness-of

Mongoid 3 - Check for uniqueness of composite key


I switched to Mongoid 3 which makes few things different :) Currently I try to check if a composite field is unique:

class Host
  include Mongoid::Document

  field :ip, :type => String
  field :port, :type => Integer
  field :username, :type => String
  field :password, :type => String

  validates_presence_of :ip
  validates_presence_of :port
end

How to get a validates_uniqueness_of therein which should check if ip and port are unique as composite field? AFAIK there was a way in Mongoid 2 to create a new _id based on multiple fields, but it seems, this was removed in Mongoid 3:

  key :ip, :port

Solution

  • Composite key support was removed in 3, since you can easily override the default _id field now and set a default value with a lambda. Try something like:

    class Host
      include Mongoid::Document
      field :_id, type: String, default: -> { ip + ":" + port }
      ...
    end
    

    You can then validate the uniqueness of this _id field.

    See the Mongoid docs for more info.