Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails MongoId组合唯一性指数_Ruby On Rails_Mongoid_Validates Uniqueness Of - Fatal编程技术网

Ruby on rails MongoId组合唯一性指数

Ruby on rails MongoId组合唯一性指数,ruby-on-rails,mongoid,validates-uniqueness-of,Ruby On Rails,Mongoid,Validates Uniqueness Of,我有三种型号 class Org include Mongoid::Document field :name, type: String embeds_many :org_groups end class OrgGroup include Mongoid::Document field :name, type: String embedded_in :org has_and_belongs_to_many :humans end class Human inc

我有三种型号

class Org
  include Mongoid::Document
  field :name, type: String
  embeds_many :org_groups
end

class OrgGroup
  include Mongoid::Document
  field :name, type: String
  embedded_in :org
  has_and_belongs_to_many :humans
end

class Human
  include Mongoid::Document
  field :name, type: String
end
一个人可以在多个组织中,但只能在一个组织组中

我需要为组织中的人员设置唯一性索引


我如何做到这一点?

您可以创建一个将由回调调用的方法。
请参阅以获取回调

如果你的条件不被尊重,你可以简单地从这个方法中提出一些东西


询问您是否需要样本。

如果您需要mongodb中的唯一索引,您可以这样做:

class Person
  include Mongoid::Document
  field :first_name
  field :last_name

  index({ first_name: 1, last_name: 1 }, { unique: true })
end
文件如下:


希望这对您有所帮助。

此解决方案非常适合模型层。谢谢我可以在MongoDB层上执行此操作吗?我在很多服务中使用单个db,在MongoDB中创建索引是个好主意,但我不知道asI不明白你说的话。我需要在MongoDB中创建唯一性索引,而不是在MongoDB中。我仍然不确定你的意思。Mongoid是用于ruby环境的MongoDB的包装器。它处理字段创建等问题。但是,如果您想在某个模型中的字段上创建索引(以便更快地搜索),可以查看以下文档: