From 3aa53449c863e49b13c9b881f7113be3f9f8e68a Mon Sep 17 00:00:00 2001 From: Marko Lovic Date: Wed, 1 Aug 2018 13:49:30 +0200 Subject: [PATCH] Fix Translatable when field values are changed to blank If we ignore all params that are blank, there is no way to "remove" an attribute (i.e. change its value to blank) On the other hand, we don't want to create new translations where all fields are empty, so the new code keeps only the blank fields which belong to existing translations. --- app/controllers/concerns/translatable.rb | 13 ++++++++++--- spec/features/translations_spec.rb | 12 ++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/app/controllers/concerns/translatable.rb b/app/controllers/concerns/translatable.rb index 5c3b1be62..21dab63f3 100644 --- a/app/controllers/concerns/translatable.rb +++ b/app/controllers/concerns/translatable.rb @@ -8,12 +8,15 @@ module Translatable private def translation_params(params) - resource_model.globalize_attribute_names.select { |k, v| params.include?(k.to_sym) && params[k].present? } + resource_model + .globalize_attribute_names + .select { |k| params[k].present? || + resource_model.translated_locales.include?(get_locale_from_attribute(k)) } end def delete_translations - locales = resource_model.globalize_locales. - select { |k, v| params[:delete_translations].include?(k.to_sym) && params[:delete_translations][k] == "1" } + locales = resource_model.translated_locales + .select { |l| params.dig(:delete_translations, l) == "1" } locales.each do |l| Globalize.with_locale(l) do resource.translation.destroy @@ -21,4 +24,8 @@ module Translatable end end + def get_locale_from_attribute(attribute_name) + locales = resource_model.globalize_locales + attribute_name.to_s.match(/(#{locales.join('|')})\Z/)&.captures&.first + end end diff --git a/spec/features/translations_spec.rb b/spec/features/translations_spec.rb index 4ff482ee4..4ac85bc4d 100644 --- a/spec/features/translations_spec.rb +++ b/spec/features/translations_spec.rb @@ -71,6 +71,18 @@ feature "Translations" do expect(page).not_to have_link "EspaƱol" end + scenario 'Change value of a translated field to blank' do + milestone.update_attributes!(status: create(:budget_investment_status)) + visit @edit_milestone_url + + fill_in 'budget_investment_milestone_description_en', with: '' + + click_button "Update milestone" + expect(page).to have_content "Milestone updated successfully" + + expect(milestone.reload.description).to be_blank + end + context "Globalize javascript interface" do scenario "Highlight current locale", :js do