Permalink
Browse files

If all translated attributes are blank then save_translations! should…

… remove rather then save.
  • Loading branch information...
1 parent 2ba83c7 commit b5565e94014388e29faee18bd717b63fcf1f45c7 @gtd gtd committed May 11, 2010
@@ -23,13 +23,20 @@ def build_translation_class(target, options, &block)
klass.class_eval do
set_table_name(options[:table_name])
+ attr_accessor :is_blank
class_inheritable_accessor :foreign_key
self.foreign_key = options[:foreign_key]
belongs_to target.name.underscore.gsub('/', '_'), :foreign_key => foreign_key
def locale; read_attribute(:locale).to_sym; end
def locale=(locale); write_attribute(:locale, locale.to_s); end
+
class_eval(&block) if block_given?
+
+ # Run after class_eval to allow a before_validation callback to unset attributes.
+ before_validation do |record|
+ record.is_blank = true if target.translated_attribute_names.all?{ |a| record[a].blank? }
+ end
end
klass
@@ -30,7 +30,14 @@ def build_translations(save_translations = false)
stash.each do |locale, attrs|
translation = record.translations.detect{ |t| locale == t.locale } || record.translations.build(:locale => locale.to_s)
attrs.each { |attr_name, value| translation[attr_name] = value }
- translation.save! if save_translations
+ if save_translations
+ translation.valid? # Trigger is_blank check.
+ if translation.is_blank
+ record.translations.delete(translation)
+ else
+ translation.save!
+ end
+ end
end
stash.clear if save_translations
end
View
@@ -473,6 +473,19 @@ class Baz < ActiveRecord::Base
assert Post.last.to_xml =~ /subject/
assert Post.last.to_xml =~ /content/
end
+
+ test "empty translations are deleted" do
+ Thing.locale = :de
+ thing = Thing.create(:content => "de subject")
+ Thing.locale = :en
+ thing.update_attributes(:content => "en subject")
+
+ assert ThingTranslation.exists?(:locale => 'en'), "English subject doesn't exist"
+
+ thing.update_attributes(:content =>"")
+
+ assert ! ThingTranslation.exists?(:locale => 'en'), "English subject exists"
+ end
end
# TODO error checking for fields that exist in main table, don't exist in
View
@@ -71,3 +71,10 @@ def custom_method_defined_by_extension
end
end
end
+
+class ThingTranslation < ActiveRecord::Base
+end
+
+class Thing < ActiveRecord::Base
+ translates :content
+end
View
@@ -65,4 +65,14 @@
t.string :locale
t.string :name
end
+
+ create_table :things, :force => true do |t|
+ t.text :content
+ end
+
+ create_table :thing_translations, :force => true do |t|
+ t.references :thing
+ t.string :locale
+ t.string :content
+ end
end

0 comments on commit b5565e9

Please sign in to comment.