From f173454b04d5156bacd7689e7460111274c5cc97 Mon Sep 17 00:00:00 2001 From: Marcus Ilgner Date: Wed, 1 Jul 2015 17:33:00 +0200 Subject: [PATCH] Fix uniqueness validator for non-paranoid associations --- lib/paranoia.rb | 6 +++++- test/paranoia_test.rb | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/lib/paranoia.rb b/lib/paranoia.rb index 5f4993b0..a89ad876 100644 --- a/lib/paranoia.rb +++ b/lib/paranoia.rb @@ -250,7 +250,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 diff --git a/test/paranoia_test.rb b/test/paranoia_test.rb index 1607bc8a..b2314644 100644 --- a/test/paranoia_test.rb +++ b/test/paranoia_test.rb @@ -37,6 +37,7 @@ def setup! 'polymorphic_models' => 'parent_id INTEGER, parent_type STRING, deleted_at DATETIME', 'namespaced_paranoid_has_ones' => 'deleted_at DATETIME, paranoid_belongs_tos_id INTEGER', 'namespaced_paranoid_belongs_tos' => 'deleted_at DATETIME, paranoid_has_one_id INTEGER', + 'unparanoid_unique_models' => 'name VARCHAR(32), paranoid_with_unparanoids_id INTEGER' }.each do |table_name, columns_as_sql_string| ActiveRecord::Base.connection.execute "CREATE TABLE #{table_name} (id INTEGER NOT NULL PRIMARY KEY, #{columns_as_sql_string})" end @@ -821,6 +822,13 @@ def test_callbacks_for_counter_cache_column_update_on_destroy # assert related_model.instance_variable_get(:@after_commit_on_destroy_callback_called) end + def test_uniqueness_for_unparanoid_associated + parent_model = ParanoidWithUnparanoids.create + related = parent_model.unparanoid_unique_models.create + # will raise exception if model is not checked for paranoia + related.valid? + end + # TODO: find a fix for Rails 4.1 if ActiveRecord::VERSION::STRING !~ /\A4\.1/ def test_counter_cache_column_update_on_really_destroy @@ -862,6 +870,16 @@ class ParanoidModel < ActiveRecord::Base acts_as_paranoid end +class ParanoidWithUnparanoids < ActiveRecord::Base + self.table_name = 'plain_models' + has_many :unparanoid_unique_models +end + +class UnparanoidUniqueModel < ActiveRecord::Base + belongs_to :paranoid_with_unparanoids + validates :name, :uniqueness => true +end + class FailCallbackModel < ActiveRecord::Base belongs_to :parent_model acts_as_paranoid @@ -874,6 +892,10 @@ class FeaturefulModel < ActiveRecord::Base validates :name, :presence => true, :uniqueness => true end +class NonParanoidChildModel < ActiveRecord::Base + validates :name, :presence => true, :uniqueness => true +end + class PlainModel < ActiveRecord::Base end