我切换到 Mongoid 3,这使得一些事情有所不同:)目前我尝试检查复合字段是否唯一:
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 中已删除:
key :ip, :port
复合键支持在 3 中被删除,因为您现在可以轻松覆盖默认 _id 字段并使用 lambda 设置默认值。尝试类似的方法:
class Host
include Mongoid::Document
field :_id, type: String, default: -> { ip + ":" + port }
...
end
然后您可以验证此 _id 字段的唯一性。
见蒙古人docs http://mongoid.org/en/mongoid/docs/documents.html了解更多信息。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)