Add validation to check translations amount on updates

In order to not allow users to remove all persited
translations from any resource. A few exceptions were
added:

* Does not apply to globalizable models without
   translatable attributes required
* Make a copy of main model error on current translations to be more realistic
This commit is contained in:
Senén Rodero Rodríguez
2019-06-07 16:45:14 +02:00
parent 12d20b481d
commit d3422acbb7
4 changed files with 55 additions and 0 deletions

View File

@@ -1,4 +1,5 @@
module Globalizable
MIN_TRANSLATIONS = 1
extend ActiveSupport::Concern
included do
@@ -8,11 +9,18 @@ module Globalizable
def locales_not_marked_for_destruction
translations.reject(&:_destroy).map(&:locale)
end
validate :check_translations_number, on: :update, if: :translations_required?
after_validation :copy_error_to_current_translation, on: :update
def description
self.read_attribute(:description).try :html_safe
end
def translations_required?
translated_attribute_names.any?{|attr| required_attribute?(attr)}
end
if self.paranoid? && translation_class.attribute_names.include?("hidden_at")
translation_class.send :acts_as_paranoid, column: :hidden_at
end
@@ -21,6 +29,38 @@ module Globalizable
private
def required_attribute?(attribute)
presence_validators = [ActiveModel::Validations::PresenceValidator,
ActiveRecord::Validations::PresenceValidator]
attribute_validators(attribute).any?{|validator| presence_validators.include? validator }
end
def attribute_validators(attribute)
self.class.validators_on(attribute).map(&:class)
end
def check_translations_number
errors.add(:base, :translations_too_short) unless traslations_count_valid?
end
def traslations_count_valid?
translations.reject(&:marked_for_destruction?).count >= MIN_TRANSLATIONS
end
def copy_error_to_current_translation
return unless errors.added?(:base, :translations_too_short)
if locales_persisted_and_marked_for_destruction.include?(I18n.locale)
locale = I18n.locale
else
locale = locales_persisted_and_marked_for_destruction.first
end
translation = translation_for(locale)
translation.errors.add(:base, :translations_too_short)
end
def searchable_globalized_values
values = {}
translations.each do |translation|