我在 2 个 mongoid 模型之间有 1 对 1 的关联,并且我不断得到重复,即有多个具有相同 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