1

Is it possibile to save all translations looking at I18n.available_locales (or maybe some other Globalize config file) when the main record is created?

I'm using Globalize in combination with Active Admin and I created a custom page only for the translations but I would like the person who needs to translate to know which are the fields yet to be translated.

This is what I'm doing now (base model) even though I'm not proud of it. It seems to be twisted for no reason I did try way simpler solution which appeared at first to be valid but they turned out not to work.

after_save :add_empty_translations

def add_empty_translations
# if the class is translatable
if (self.class.translates?)
  # get available locales 
  locales = I18n.available_locales.map do |l| l.to_s end
  # get foreign key for translated table
  foreign_key = "#{self.class.to_s.underscore}_id"
  # get translated columns
  translated_columns = self.class::Translation.column_names.select do |col| 
    !['id', 'created_at', 'updated_at', 'locale', "#{self.class.to_s.underscore}_id"].include? col 
  end
  # save current locale
  current_locale = I18n.locale
  # foreach available locale check if column was difined by user
  locales.each do |l|
    I18n.locale = l
    add_translation = true
    translated_columns.each do |col|
      add_translation = add_translation && self[col].nil?
    end
    if (add_translation)
      payload = {}
      payload[foreign_key] = self.id
      payload['locale'] = l
      self.class::Translation.create(payload)
     end
   end
   #restore locale
   I18n.locale = current_locale
 end
end

Is there a way to do it with globalize?

4

1 回答 1

3

由于上述解决方案并非一直有效,因此我最终修补了 gem 本身,如下所示:

Globalize::ActiveRecord::Adapter.module_eval do 
  def save_translations!
    # START PATCH
    translated_columns = self.record.class::Translation.column_names.select do |col| 
        !['id', 'created_at', 'updated_at', 'locale', "#{self.record.class.to_s.underscore}_id"].include? col 
    end

    payload = {}
    translated_columns.each do |column|
        payload[column] = ""
    end

    I18n.available_locales.each do |l|
        add_translation = true
        translated_columns.each { |column| add_translation &&= stash[l][column].nil? }
        if (record.translations_by_locale[l].nil? && add_translation)
            stash[l] = payload
        end
    end
    # END PATCH

    stash.each do |locale, attrs|
        next if attrs.empty?

        translation = record.translations_by_locale[locale] ||
            record.translations.build(locale: locale.to_s)

        attrs.each do |name, value|
            value = value.val if value.is_a?(Arel::Nodes::Casted)
            translation[name] = value
        end
    end
    reset
  end
end
于 2017-05-24T21:23:24.193 回答