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

时间:2018-02-20 09:29:46

标签: ruby-on-rails 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

1 个答案:

答案 0 :(得分:2)

您需要在该字段下创建索引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中创建索引