2017-05-24 69 views
1

保存所有翻譯當創建主記錄時是否可以保存查看I18n.available_locales(或者其他一些Globalize配置文件)的所有翻譯?Globalize rails:通過檢查I18n.available_locales

我將Activeize與Active Admin結合使用,我爲翻譯創建了自定義頁面,但我希望需要翻譯的人員知道哪些字段尚未翻譯。

這就是我現在正在做的(基本模型),儘管我並不以此爲榮。這似乎是扭曲的,沒有理由,我嘗試了更簡單的解決方案,出現在第一個是有效的,但他們竟然不工作。

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 

有沒有辦法做到全球化?

回答

1

由於上述方案是行不通的所有的時候,我結束了修補寶石本身就像如下:

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