Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
johnnylai committed Mar 13, 2015
1 parent 0e0a60e commit 0a33396
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
13 changes: 13 additions & 0 deletions lib/paranoia.rb
Original file line number Diff line number Diff line change
Expand Up @@ -187,4 +187,17 @@ def paranoia_column
end
end

module ActiveRecord
module Validations
class UniquenessValidator < ActiveModel::EachValidator
protected
def build_relation_with_paranoia(klass, table, attribute, value)
relation = build_relation_without_paranoia(klass, table, attribute, value)
relation.and(klass.quoted_table_name + ".#{klass.paranoia_column} IS NULL")
end
alias_method_chain :build_relation, :paranoia
end
end
end

require 'paranoia/rspec' if defined? RSpec
10 changes: 9 additions & 1 deletion test/paranoia_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
ActiveRecord::Base.connection.execute 'CREATE TABLE callback_models (id INTEGER NOT NULL PRIMARY KEY, deleted_at DATETIME)'
ActiveRecord::Base.connection.execute 'CREATE TABLE fail_callback_models (id INTEGER NOT NULL PRIMARY KEY, deleted_at DATETIME)'
ActiveRecord::Base.connection.execute 'CREATE TABLE related_models (id INTEGER NOT NULL PRIMARY KEY, parent_model_id INTEGER NOT NULL, deleted_at DATETIME)'
ActiveRecord::Base.connection.execute 'CREATE TABLE employers (id INTEGER NOT NULL PRIMARY KEY, deleted_at DATETIME)'
ActiveRecord::Base.connection.execute 'CREATE TABLE employers (id INTEGER NOT NULL PRIMARY KEY, deleted_at DATETIME), name VARCHAR(10))'
ActiveRecord::Base.connection.execute 'CREATE TABLE employees (id INTEGER NOT NULL PRIMARY KEY, deleted_at DATETIME)'
ActiveRecord::Base.connection.execute 'CREATE TABLE jobs (id INTEGER NOT NULL PRIMARY KEY, employer_id INTEGER NOT NULL, employee_id INTEGER NOT NULL, deleted_at DATETIME)'
ActiveRecord::Base.connection.execute 'CREATE TABLE custom_column_models (id INTEGER NOT NULL PRIMARY KEY, destroyed_at DATETIME)'
Expand Down Expand Up @@ -449,6 +449,13 @@ def test_observers_not_notified_if_not_supported
# essentially, we're just ensuring that this doesn't crash
end

def test_validates_uniqueness_only_checks_non_deleted_records
a = Employer.create!(name: "A")
a.destroy
b = Employer.new(name: "A")
assert b.valid?
end

private
def get_featureful_model
FeaturefulModel.new(:name => 'not empty')
Expand Down Expand Up @@ -513,6 +520,7 @@ class RelatedModel < ActiveRecord::Base

class Employer < ActiveRecord::Base
acts_as_paranoid
validates_uniqueness_of :name
has_many :jobs
has_many :employees, :through => :jobs
end
Expand Down

0 comments on commit 0a33396

Please sign in to comment.