mongoid-4 如何验证 1 对 1 关联中 belongs_to 的唯一性

mongoid-4 how to validate uniqueness of belongs_to in 1 to 1 association

我在 2 个 mongoid 模型之间有一对一的关联,并且我不断得到重复项,即有多个具有相同 parent_id(即用户)的子记录(卡片)。我已尝试验证 belongs_to 关联的唯一性,如下所示,但它不起作用。

 class User
   include Mongoid::Document
   field :name, type: String 
   has_one :card
 end

第二个模型:

 class Card
   include Mongoid::Document
   field :name, type: String 
   belongs_to :user

   validates :user, :uniqueness => {:scope => :user_has_child}

   def user_has_child
     q = Segment.where(drop_id: {'$ne' =>  nil})
     s = q.map(&:drop_id)
     errors.add(:drop_id, "this user already has a card") if s.include?(:drop_id)
   end

 end

语法更简单。您只想确保没有 2 个文档具有相同的 user_id

class Card
  belongs_to :user

  validates_uniqueness_of :user

如果你想要 n 个字段的元组的唯一性,你需要使用范围。例如,如果一个用户每年最多可以拥有一张卡,则可以写成

class Card
 field :year
 belongs_to :user  

 validates_uniqueness_of :user, scope: [:year] # A user can have one card per year

请注意,保存模型时会应用验证,即。您尝试坚持更改。如果某些验证失败,调用 .save 将 return true 或 false,但 内存中的对象始终被修改 !就是这样,例如,您可以在 HTML 输入字段中显示以前的值,这样用户就知道他写了什么并且可以修复它(否则他必须重新编写所有信息以防万一一个错误)

此外,Mongoid by default handles dirty tracking(现在这是 v5.0 的文档,但它与 Mongoid 4 相同)。也就是说,你可以在内存中的对象上调用.changed? .changes, etc,看看与DB中的对象相比有什么变化。