Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 validate uniqueness ignores default scope on model

I'm using the permanent_records gem in my rails 3.0.10 app, to prevent hard deletes and it seems rails is ignoring my default scope in checking uniqueness

# user.rb
class User < AR::Base
  default_scope where(:deleted_at => nil)

  validates_uniqueness_of :email # done by devise
end

in my rails console trying to find a user by email that has been deleted results in null, but when signing up for a new account with a deleted email address results in a validation error on the email field.

This is also the case for another model in my app

# group.rb
class Group < AR::Base
  default_scope where(:deleted_at => nil)
  validates_uniqueness_of :class_name
end

and that is the same case as before, deleting a group then trying to find it by class name results in nil, however when I try to create a group with a known deleted class name it fails validation.

Does anyone know if I am doing something wrong or should I just write custom validators for this behavior?

like image 720
Jimmy Avatar asked Aug 27 '11 04:08

Jimmy


1 Answers

Try scoping the uniqueness check with deleted_at

validates_uniqueness_of : email, :scope => :deleted_at

This can allow two records with the same email value as long as deleted_at field is different for both. As long as deleted at is populated with the correct timestamp, which I guess permanent_records gem does, this should work.

like image 108
dexter Avatar answered Sep 23 '22 11:09

dexter