3

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
halfer
  • 19,824
  • 17
  • 99
  • 186
ctp
  • 1,077
  • 1
  • 10
  • 28

1 Answers1

6

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.

Vickash
  • 1,076
  • 8
  • 8
  • Many thanks for the answer. Lot of things changed in Mongoid 3 :) But it seems to be what I am looking for. – ctp Aug 22 '12 at 12:11
  • There is a syntax error in the code above, the correct code is: ``field :_id, type: String, default: -> { ip + ":" + port }`` (note the colon after default) I'd have edited the original answer but theres a 6 character cap. – wintersolutions May 10 '13 at 16:54