I'm not sure if this is a bug or not. It certainly caught me off-guard.
class Bar < ActiveRecord::Base
class Foo < ActiveRecord::Base
bars.create!(:something => something)
abar = bars.build(:something => something)
# those are both saved, no errors
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?
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
p.s. On a side note, I remember facing something similar with STI and
I’ve got a patch on the way for this same bug, if anyone wants to collaborate
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.
I've just committed a patch:
Let me know if this fixes what you're seeing too.