Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #9235 (closed defect: fixed)

Opened 2 years ago

Last modified 1 year ago

[PATCH] validates_uniqueness_of with implicit scoping + class methods on has_many associations

Reported by: nik.wakelin Assigned to: nzkoz
Priority: normal Milestone: 2.x
Component: ActiveRecord Version: edge
Severity: normal Keywords: patch
Cc: ianb@nulogy.com

Description

When you have a setup like the following:

 class Reseller < ActiveRecord::Base
   has_many :accounts
 end

 class Account < ActiveRecord::Base
   
   validates_uniqueness_of :domain

   def self.create_account(params)
     Account.create!(params)
   end

 end

The validates_uniqueness_of call for "domain" gets scoped by the Reseller (i.e SELECT COUNT(*) FROM accounts WHERE domain = "blah.com" AND reseller_id = 1). Which isn't what I expected :)

This ticket just breaks out of implicit scoping for the vuo call.

Attachments

vuo_scoping_with_magic_scope.diff (3.1 kB) - added by nik.wakelin on 08/10/07 04:51:02.
validates_uniqueness_of_with_exclusive_scope.diff (1.8 kB) - added by cavalle on 03/24/08 21:45:49.
Fixing indentantion error
validates_uniqueness_of_with_exclusive_scope.2.diff (1.9 kB) - added by cavalle on 03/31/08 12:34:48.
Updated to edge

Change History

08/10/07 04:51:02 changed by nik.wakelin

  • attachment vuo_scoping_with_magic_scope.diff added.

03/19/08 15:37:04 changed by ian_bailey

  • cc set to ianb@nulogy.com.

I can reproduce this with the following steps:

r1 = Reseller.create!
r2 = Reseller.create!
r1.accounts.create! :domain => "blah.com"
r2.accounts.create! :domain => "blah.com"

Both accounts are created successfully. This is happening because validates_uniqueness_of uses find(:first), which will use the current scope. In the above example, this will scope the check to just the one account.

03/24/08 00:12:59 changed by cavalle

  • keywords set to patch.
  • summary changed from validates_uniqueness_of with implicit scoping + class methods on has_many associations to [PATCH] validates_uniqueness_of with implicit scoping + class methods on has_many associations.

Patch updated for trunk and test changed

03/24/08 21:45:49 changed by cavalle

  • attachment validates_uniqueness_of_with_exclusive_scope.diff added.

Fixing indentantion error

03/26/08 17:18:18 changed by danger

+1 Great patch. Considering validates_uniqueness_of allows a :scope option it wouldn't make any sense to have mysterious scoping on this.

03/31/08 12:34:48 changed by cavalle

  • attachment validates_uniqueness_of_with_exclusive_scope.2.diff added.

Updated to edge

03/31/08 12:57:50 changed by pratik

  • status changed from new to closed.
  • resolution set to fixed.

(In [9168]) Ensure that validates_uniqueness_of works with with_scope. Closes #9235. [nik.wakelin, cavalle]