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的包装器。它处理字段创建等问题。但是,如果您想在某个模型中的字段上创建索引(以便更快地搜索),可以查看以下文档: