diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index cfd3b9fb38a9d3f3ea192bbffbc45525909d6590..9ed3579318cd9a7ff948ee8f1632b52ada3caaf2 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,5 +1,7 @@ *SVN* +* Ensure that validates_uniqueness_of works with with_scope. Closes #9235. [nik.wakelin, cavalle] + * Partial updates include only unsaved attributes. Off by default; set YourClass.partial_updates = true to enable. [Jeremy Kemper] * Removing unnecessary uses_tzinfo helper from tests, given that TZInfo is now bundled [Geoff Buesing] diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 5e2f710db65513a76f0b3bba39a3ff4f5a3fa1bc..72c48d1e2a0c89f1c13a64029b8cf0697866a977 100755 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -654,13 +654,15 @@ def validates_uniqueness_of(*attr_names) condition_params << record.send(:id) end - results = connection.select_all( - construct_finder_sql( - :select => "#{attr_name}", - :from => "#{finder_class.quoted_table_name}", - :conditions => [condition_sql, *condition_params] + results = finder_class.with_exclusive_scope do + connection.select_all( + construct_finder_sql( + :select => "#{attr_name}", + :from => "#{finder_class.quoted_table_name}", + :conditions => [condition_sql, *condition_params] + ) ) - ) + end unless results.length.zero? found = true diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index d0b4902bceefad0d7c881bc73fd0d7a1945cf967..1bcd72c71fda26c68b44b2729ebff62313c71bf7 100755 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -467,6 +467,16 @@ def test_validate_uniqueness_with_non_standard_table_names assert i1.errors.on(:value), "Should not be empty" end + def test_validates_uniqueness_inside_with_scope + Topic.validates_uniqueness_of(:title) + + Topic.with_scope(:find => { :conditions => { :author_name => "David" } }) do + t1 = Topic.new("title" => "I'm unique!", "author_name" => "Mary") + assert t1.save + t2 = Topic.new("title" => "I'm unique!", "author_name" => "David") + assert !t2.valid? + end + end def test_validate_straight_inheritance_uniqueness w1 = IneptWizard.create(:name => "Rincewind", :city => "Ankh-Morpork")