Reputation: 2700
Is it possible 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 defined 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?
Upvotes: 1
Views: 810
Reputation: 2700
Since the above solution wasn't working all the times I ended up patching the gem itself like it follows:
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
Upvotes: 3