mardi 4 août 2015

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

I have a 1-to-1 association between 2 mongoid models and I keep getting duplicates, that is having more than one child record(card) with same parent_id(that is user). I have tried validating uniqueness of the belongs_to association has shown below, but it doesn't work.

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

The second model:

 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



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire