如何使用 ruby mongoid 在字段上创建唯一约束?

How to create unique constrain on a field using ruby mongoid?

您好,我想在我正在使用 Ruby on Rails 版本 5 和 mongodb 我正在使用 mongoid

的字段上创建唯一约束
 class SkillSet
   include Mongoid::Document
   field :name, type: String # this field has to be unique

   def some_method
   end
 end

您需要在该字段上创建索引 mongoid-index 下面是更新后的代码

class SkillSet
  include Mongoid::Document
  field :name, type: String 
  index({ name: 1 }, { unique: true, name: "name_index" })


  def some_method
  end
end

运行 这个 rake db:mongoid:create_indexes 在 mongodb

中创建索引