Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

added patch for uniqueness validation on translated attributes, fixes #7

  • Loading branch information...
commit 9fd323976c89a5e6045528a2056f6c8a1f695a57 1 parent 6699cdf
@shioyama shioyama authored
View
1  lib/globalize.rb
@@ -1,6 +1,7 @@
require 'active_record'
require 'patches/active_record/xml_attribute_serializer'
require 'patches/active_record/query_method'
+require 'patches/active_record/uniqueness_validator'
module Globalize
autoload :ActiveRecord, 'globalize/active_record'
View
24 lib/patches/active_record/uniqueness_validator.rb
@@ -0,0 +1,24 @@
+require 'active_record/validations/uniqueness.rb'
+
+ActiveRecord::Validations::UniquenessValidator.class_eval do
+ def validate_each_with_translations(record, attribute, value)
+ klass = record.class
+ if klass.translates? && klass.translated_attribute_names.include?(attribute.to_sym)
+ finder_class = klass.translation_class
+ table = finder_class.arel_table
+
+ relation = build_relation(finder_class, table, attribute, value).and(table[:locale].eq(Globalize.locale.to_s))
+ relation = relation.and(table[:"#{klass.name.downcase}_id"].not_eq(record.send(:id))) if record.persisted?
+
+# TODO: add scope with translated attributes
+
+ if finder_class.unscoped.where(relation).exists?
+ record.errors.add(attribute, :taken, options.except(:case_sensitive, :scope).merge(:value => value))
+ end
+
+ else
+ validate_each_without_translations(record, attribute, value)
+ end
+ end
+ alias_method_chain :validate_each, :translations
+end
View
19 test/globalize3/validations_test.rb
@@ -75,18 +75,13 @@ def teardown
assert Validatee.new(:string => '1').valid?
end
- # This doesn't pass and Rails' validates_uniqueness_of implementation doesn't
- # seem to be extensible easily. One can work around that by either defining
- # a custom validation on the Validatee model itself, or by using validates_uniqueness_of
- # on Validatee::Translation.
- #
- # test "validates_uniqueness_of" do
- # Validatee.class_eval { validates_uniqueness_of :string }
- # Validatee.create!(:string => 'a')
- # assert !Validatee.new(:string => 'a').valid?
- # assert Validatee.new(:string => 'b').valid?
- # end
+ test "validates_uniqueness_of" do
+ Validatee.class_eval { validates_uniqueness_of :string }
+ Validatee.create!(:string => 'a')
+ assert !Validatee.new(:string => 'a').valid?
+ assert Validatee.new(:string => 'b').valid?
+ end
# test "validates_associated" do
# end
-end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.