Skip to content
This repository has been archived by the owner on Apr 17, 2018. It is now read-only.

Uniqueness check should only be skipped if the field is blank #61

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/dm-validations/validators/uniqueness_validator.rb
Expand Up @@ -27,7 +27,7 @@ def call(target)


def valid?(target) def valid?(target)
value = target.validation_property_value(field_name) value = target.validation_property_value(field_name)
return true if optional?(value) return true if optional?(value) && DataMapper::Ext.blank?(value)


opts = { opts = {
:fields => target.model.key(target.repository.name), :fields => target.model.key(target.repository.name),
Expand Down
14 changes: 14 additions & 0 deletions spec/fixtures/corporate_world.rb
Expand Up @@ -34,6 +34,20 @@ class User
validates_uniqueness_of :user_name, :when => :signing_up_for_department_account, :scope => [:department] validates_uniqueness_of :user_name, :when => :signing_up_for_department_account, :scope => [:department]
validates_uniqueness_of :user_name, :when => :signing_up_for_organization_account, :scope => [:organisation] validates_uniqueness_of :user_name, :when => :signing_up_for_organization_account, :scope => [:organisation]
end end

class Manager
include DataMapper::Resource

property :id, Serial
property :name, String
property :title, String

validates_uniqueness_of :title, :if => :has_title?

def has_title?
!title.nil? && title != ''
end
end
end end
end end
end end
31 changes: 31 additions & 0 deletions spec/integration/uniqueness_validator/uniqueness_validator_spec.rb
Expand Up @@ -113,4 +113,35 @@
end end
end end


describe 'DataMapper::Validations::Fixtures::Manager' do
before :all do
DataMapper::Validations::Fixtures::Manager.destroy!

DataMapper::Validations::Fixtures::Manager.create(:name => "John", :title => 'CEO').should be_saved
end

describe "with unique title" do
before do
@model = DataMapper::Validations::Fixtures::Manager.new(:name => 'Bob', :title => 'COO')
end

it_should_behave_like "valid model"
end

describe "with a duplicate title" do
before do
@model = DataMapper::Validations::Fixtures::Manager.new(:name => 'Bob', :title => 'CEO')
end

it_should_behave_like "invalid model"
end

describe "with no title" do
before do
@model = DataMapper::Validations::Fixtures::Manager.new(:name => 'Bob')
end

it_should_behave_like "valid model"
end
end
end end