문제

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
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top