代码之家  ›  专栏  ›  技术社区  ›  shaan

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

  •  1
  • shaan  · 技术社区  · 7 年前

    您好,我想在我使用的字段上创建唯一约束 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
    
    1 回复  |  直到 7 年前
        1
  •  3
  •   ashwintastic    7 年前

    您需要创建索引 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中创建索引