Mongoid 3 - Check for uniqueness of composite key

感情迁移 提交于 2019-12-10 21:16:24

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/11856015/mongoid-3-check-for-uniqueness-of-composite-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!