如何在 mongoid 中强制执行唯一的嵌入文档

2024-02-14

我有以下型号

class Person 
  include Mongoid::Document
  embeds_many :tasks
end

class Task
  include Mongoid::Document
  embedded_in :commit, :inverse_of => :tasks
  field :name
end

我如何确保以下事项?

person.tasks.create :name => "create facebook killer"
person.tasks.create :name => "create facebook killer"

person.tasks.count == 1

different_person.tasks.create :name => "create facebook killer"
person.tasks.count == 1
different_person.tasks.count == 1

即任务名称在特定人员中是唯一的


查看了有关索引的文档后,我认为以下内容可能有效:

class Person 
  include Mongoid::Document
  embeds_many :tasks

  index [
      ["tasks.name", Mongo::ASCENDING], 
      ["_id", Mongo::ASCENDING]
  ], :unique => true
end

but

person.tasks.create :name => "create facebook killer"
person.tasks.create :name => "create facebook killer"

仍然产生一个副本。


上面在 Person 中显示的索引配置将转换为 for mongodb

db.things.ensureIndex({firstname : 1, 'tasks.name' : 1}, {unique : true})

你不能在任务上放置一个验证器吗?

validates :name, :uniqueness => true

这应该确保父文档中的唯一性。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 mongoid 中强制执行唯一的嵌入文档 的相关文章

随机推荐