Mongoid 3-检查组合键的唯一性 [英] Mongoid 3 - Check for uniqueness of composite key
问题描述
我切换到Mongoid 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
如何在其中获取validates_uniqueness_of,它应该检查ip和port是否作为复合字段唯一? AFAIK在Mongoid 2中提供了一种基于多个字段创建新_id的方法,但似乎在Mongoid 3中已将其删除:
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
推荐答案
在3中删除了复合键支持,因为您现在可以轻松覆盖默认的_id字段并使用lambda设置默认值.尝试类似的东西:
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
然后您可以验证此_id字段的唯一性.
You can then validate the uniqueness of this _id field.
有关更多信息,请参见Mongoid docs .
See the Mongoid docs for more info.
这篇关于Mongoid 3-检查组合键的唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!