|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +module ActiveAdmin |
| 3 | + module Globalize3 |
| 4 | + module FilterEmptyTranslations |
| 5 | + private |
| 6 | + # Activeadmin-globalize3 renders inputs for all translations, |
| 7 | + # resulting in many empty translations being created by globalize. |
| 8 | + # |
| 9 | + # For instance, given the available locales L1, L2 and L2, the |
| 10 | + # following params would be submitted on 'create': |
| 11 | + # |
| 12 | + # { |
| 13 | + # : |
| 14 | + # MODEL => { |
| 15 | + # "translations_attributes" => { |
| 16 | + # "0" => { |
| 17 | + # "locale"=>"L1", "id" => "", ATTR1 => "", ATTR2 => "", ... |
| 18 | + # } |
| 19 | + # "1" => { |
| 20 | + # "locale"=>"L2", "id" => "", ATTR1 => "", ATTR2 => "", ... |
| 21 | + # } |
| 22 | + # "2" => { |
| 23 | + # "locale"=>"L3", "id" => "", ATTR1 => "", ATTR2 => "", ... |
| 24 | + # } |
| 25 | + # } |
| 26 | + # } |
| 27 | + # : |
| 28 | + # } |
| 29 | + # |
| 30 | + # Given these parameters, globalize3 would create a record for every |
| 31 | + # possible translation - even empty ones. |
| 32 | + # |
| 33 | + # This filter removes all empty and unsaved translations from params |
| 34 | + # and marks empty and saved translation for deletion. |
| 35 | + def filter_empty_translations |
| 36 | + model_class = controller_name.classify.safe_constantize |
| 37 | + if model_class.nil? or not model_class.translates? |
| 38 | + return |
| 39 | + end |
| 40 | + model = controller_name.singularize.to_sym |
| 41 | + params[model][:translations_attributes].each do |k,v| |
| 42 | + if v.values[2..-1].all?(&:blank?) |
| 43 | + if v[:id].empty? |
| 44 | + params[model][:translations_attributes].delete(k) |
| 45 | + else |
| 46 | + params[model][:translations_attributes][k]['_destroy'] = '1' |
| 47 | + end |
| 48 | + end |
| 49 | + end |
| 50 | + end |
| 51 | + end |
| 52 | + end |
| 53 | +end |
0 commit comments