Skip to content

Commit

Permalink
Don't hit database on uniqueness validation if the field has not chan…
Browse files Browse the repository at this point in the history
…ged. Fixes #1576.
  • Loading branch information
durran committed Jan 10, 2012
1 parent d523357 commit 44a3b04
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 4 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Expand Up @@ -47,6 +47,9 @@ For instructions on upgrading to newer versions, visit

### Resolved Issues

* \#1576 Don't hit database on uniqueness validation if the field getting
validated has not changed.

* \#1568 Fallback to development environment with warning when no env configured.

* \#1557 Internal strategy class no longer conflicts with models.
Expand Down
1 change: 1 addition & 0 deletions lib/mongoid/validations/uniqueness.rb
Expand Up @@ -41,6 +41,7 @@ def setup(klass)
#
# @since 1.0.0
def validate_each(document, attribute, value)
return unless document.send("#{attribute}_changed?")
if document.embedded?
return if skip_validation?(document)
relation = document._parent.send(document.metadata.name)
Expand Down
23 changes: 21 additions & 2 deletions spec/functional/mongoid/validations/uniqueness_spec.rb
Expand Up @@ -65,8 +65,27 @@
Dictionary.create(:name => "Oxford")
end

it "returns true" do
dictionary.should be_valid
context "when the field has changed" do

it "returns true" do
dictionary.should be_valid
end
end

context "when the field has not changed" do

let(:from_db) do
Dictionary.find(dictionary.id)
end

it "returns true" do
from_db.should be_valid
end

it "does not touch the database" do
Dictionary.expects(:where).never
from_db.valid?
end
end
end
end
Expand Down
4 changes: 2 additions & 2 deletions spec/unit/mongoid/validations/uniqueness_spec.rb
Expand Up @@ -11,7 +11,7 @@
context "when the document is the root" do

let(:dictionary) do
Dictionary.new(:year => 1999)
Dictionary.new(:year => 1999, :name => "")
end

let(:criteria) do
Expand Down Expand Up @@ -116,7 +116,7 @@
end

let(:definition) do
word.definitions.build
word.definitions.build(:description => "")
end

let(:criteria) do
Expand Down

0 comments on commit 44a3b04

Please sign in to comment.