2017-05-24 1 views
1

기본 레코드가 작성 될 때 I18n.available_locales (또는 다른 일부 Globalize 구성 파일)을보고 모든 번역을 저장할 수 있습니까?세계화 레일 : I18n.available_locales를 확인하여 모든 번역을 저장하십시오.

Active Admin과 조합하여 Globalize를 사용하고 있으며 번역에 대해서만 사용자 정의 페이지를 만들었지 만 번역해야하는 사람이 아직 번역 할 필드가 무엇인지 알고 싶습니다.

이것이 내가 자랑스럽지 않지만 지금 내가하고있는 것 (기본 모델)입니다. 그것은 아무 이유없이 왜곡 된 것 같습니다. 처음에는 유효했던 간단한 솔루션을 시도했지만 작동하지 않는 것으로 나타났습니다.

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