possible bug with validates_uniqueness_of scoping?

Hey,

I'm not sure if this is a bug or not. It certainly caught me off-guard.

class Bar < ActiveRecord::Base
   belongs_to :foo
   validates_uniqueness_of :something
end

class Foo < ActiveRecord::Base
   has_many :bars

   def boo(something)
     bars.create!(:something => something)
   end

   def yay(something)
     abar = bars.build(:something => something)
     abar.save!
   end
end

Foo.find(1).boo('oh dear')
Foo.find(2).boo('oh dear')
# those are both saved, no errors

Foo.find(1).yay('huzzah')
Foo.find(2).yay('huzzah') #=> fails, validates_uniqueness_of fires an error.

The reason for the difference is that the find() issued by validates_uniqueness_of is *scoped* to has_many(:bars) during the call to bars.create!().

What does everyone think? Should validates_uniqueness_of ignore with_scope() values when checking for conflicting records?

Thanks,
Trevor

What does everyone think? Should validates_uniqueness_of ignore
with_scope() values when checking for conflicting records?

Yes. This is clearly a bug to my eyes. You should probably submit a
patch. If not, let it be known here and someone else probably will :slight_smile:

p.s. On a side note, I remember facing something similar with STI and
validates_uniquness_of

Hey All,

I’ve got a patch on the way for this same bug, if anyone wants to collaborate :slight_smile:

Cheers,

Nik

Nik,

that’s good news that you’ve got a patch.

One of the reasons I asked before putting together a patch is because I didn’t want to go through the effort if the behavior wasn’t considered undesirable - and I can work around it just fine in my own code.

So if you’ve already got something in the works then great - I’ll +1 your patch (after testing it in my own env, of course) when you submit.

Regards,

Trevor

Hi Trevor,

I've just committed a patch:

http://dev.rubyonrails.org/ticket/9235

Let me know if this fixes what you're seeing too.

Cheers,

Nik