diff --git a/app/controllers/admin/rules_controller.rb b/app/controllers/admin/rules_controller.rb index f355aa230b2..74a6c3ebb29 100644 --- a/app/controllers/admin/rules_controller.rb +++ b/app/controllers/admin/rules_controller.rb @@ -3,6 +3,7 @@ module Admin class RulesController < BaseController before_action :set_rule, except: [:index, :new, :create] + before_action :build_missing_translations, only: :edit def index authorize :rule, :index? @@ -17,9 +18,6 @@ module Admin def edit authorize @rule, :update? - - missing_languages = RuleTranslation.languages - @rule.translations.pluck(:language) - missing_languages.each { |lang| @rule.translations.build(language: lang) } end def create @@ -78,5 +76,9 @@ module Admin params .expect(rule: [:text, :hint, :priority, translations_attributes: [[:id, :language, :text, :hint, :_destroy]]]) end + + def build_missing_translations + @rule.untranslated_languages.each { |language| @rule.translations.build(language:) } + end end end diff --git a/app/models/rule.rb b/app/models/rule.rb index 672bef7d1ea..2287e61871b 100644 --- a/app/models/rule.rb +++ b/app/models/rule.rb @@ -44,4 +44,8 @@ class Rule < ApplicationRecord @cached_translations ||= {} @cached_translations[locale] ||= translations.for_locale(locale).by_language_length.first || translations.build(language: locale, text: text, hint: hint) end + + def untranslated_languages + RuleTranslation.excluding(translations).languages + end end diff --git a/spec/models/rule_spec.rb b/spec/models/rule_spec.rb index e6a2d807cbf..9eb39089687 100644 --- a/spec/models/rule_spec.rb +++ b/spec/models/rule_spec.rb @@ -47,4 +47,28 @@ RSpec.describe Rule do expect(rule.translation_for(:'fr-CA')).to have_attributes(text: translation.text, hint: translation.hint) end end + + describe '#untranslated_languages' do + subject { rule.untranslated_languages } + + let(:rule) { Fabricate :rule } + + context 'when there are no translations' do + it { is_expected.to be_an(Array).and(be_empty) } + end + + context 'when there are translations' do + let(:linked_to_rule_translation) { Fabricate :rule_translation, language: 'es', rule: } + let!(:missing_translation) { Fabricate :rule_translation, language: 'fr' } + let!(:discarded_rule_translation) { Fabricate :rule_translation, language: 'gb', rule: discarded_rule } + let(:discarded_rule) { Fabricate :rule, deleted_at: 5.days.ago } + + it 'returns language strings of missing translations' do + expect(subject) + .to include(missing_translation.language) + .and not_include(linked_to_rule_translation.language) + .and not_include(discarded_rule_translation.language) + end + end + end end