Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix uniqueness validator for non-paranoid models. #256

Open
wants to merge 1 commit into
base: rails3
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/paranoia.rb
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,11 @@ 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.arel_table[klass.paranoia_column].eq(nil))
if klass.respond_to?(:paranoia_column)
relation.and(klass.arel_table[klass.paranoia_column].eq(nil))
else
relation
end
end
alias_method_chain :build_relation, :paranoia
end
Expand Down
11 changes: 11 additions & 0 deletions test/paranoia_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
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)'
ActiveRecord::Base.connection.execute 'CREATE TABLE non_paranoid_models (id INTEGER NOT NULL PRIMARY KEY, parent_model_id INTEGER)'
ActiveRecord::Base.connection.execute 'CREATE TABLE non_paranoid_unique_models (id INTEGER NOT NULL PRIMARY KEY, name VARCHAR(10))'

class ParanoiaTest < Test::Unit::TestCase
def test_plain_model_class_is_not_paranoid
Expand Down Expand Up @@ -448,6 +449,12 @@ def test_validates_uniqueness_still_works_on_non_deleted_records
refute b.valid?
end

def test_validates_uniqueness_still_works_on_non_paranoid_models
a = NonParanoidUniqueModel.create!(name: "A")
b = NonParanoidUniqueModel.new(name: "A")
refute b.valid?
end

private
def get_featureful_model
FeaturefulModel.new(:name => 'not empty')
Expand Down Expand Up @@ -535,6 +542,10 @@ class CustomColumnModel < ActiveRecord::Base
class NonParanoidModel < ActiveRecord::Base
end

class NonParanoidUniqueModel < ActiveRecord::Base
validates :name, :uniqueness => true
end

class ParanoidModelWithObservers < ParanoidModel
def observers_notified
@observers_notified ||= []
Expand Down