Mongoid: validates_uniqueness_of validation is only triggered when a specific field is changed

I have a unique constraint defined using a condition. But the following test fails:

class Dummy include Mongoid::Document field :name, :type => String field :status, :type => Boolean validates_uniqueness_of :name, if: :status end describe "UniquenessValidator" do let!(:d1) { Dummy.create!(name: 'NAME_1', status: true) } let!(:d2) { Dummy.create!(name: 'NAME_1', status: false) } it "should raise an error" do expect { d2.status = true d2.save! }.to raise_error end end 

So how is name_changed? is false, validation does not occur, and therefore the condition of uniqueness is not verified.

This is mistake? Or am I forgetting something? I assume this is an optimization to avoid running a check every time an item has been changed.

In this case, what is a good way to initiate a check when the status changes?

Thanks!

+7
ruby mongoid
source share
2 answers

As a case with the region, I would advise you to create your own validator class for it, something like this should work:

 class NameUniquenessValidator < Mongoid::Validatable::UniquenessValidator private def validation_required?(document, attribute) return true "name" == attribute.to_s super end end class Dummy include Mongoid::Document field :name, :type => String field :status, :type => Boolean validates_with(NameUniquenessValidator, :name, if: :status) end 
+5
source share

You are updating the status field, so you need to confirm this field. You can do something like this:

 class Dummy include Mongoid::Document field :name, :type => String field :status, :type => Boolean validates_uniqueness_of :name, if: :status validates_uniqueness_of :status, scope: :name, if: :status end 

I do not know if it is possible to force mongoid to check all fields when updating a single field.

+1
source share

All Articles