0

我使用 globalize2 将 i18n 添加到旧站点。西班牙语中已经有很多内容,但是它没有存储在 globalize2 表中。有没有办法通过在 Rails 中迁移将此内容转换为 globalize2?

问题是我无法访问存储的内容:

>> Panel.first
=> #<Panel id: 1, name: "RT", description: "asd", proje....
>> Panel.first.name
=> nil
>> I18n.locale = nil
=> nil
>> Panel.first.name
=> nil

有任何想法吗?

4

1 回答 1

1

我确定您以一种或另一种方式解决了这个问题,但是就这样。您应该能够使用该read_attribute方法挖掘出您要查找的内容。

我只是使用以下内容将主表中的内容迁移到 globalize2 翻译表中。

  1. 将适当的translates行添加到您的模型中。
  2. 将以下内容放入config/initializers/globalize2_data_migration.rb

    require 'globalize'
    module Globalize
      module ActiveRecord
        module Migration
    
          def move_data_to_translation_table
            klass = self.class_name.constantize
            return unless klass.count > 0
            translated_attribute_columns = klass.first.translated_attributes.keys
            klass.all.each do |p|
              attribs = {}
              translated_attribute_columns.each { |c| attribs[c] = p.read_attribute(c) }
              p.update_attributes(attribs)
            end
          end
    
          def move_data_to_model_table
            # Find all of the translated attributes for all records in the model.
            klass = self.class_name.constantize
            return unless klass.count > 0
            all_translated_attributes = klass.all.collect{|m| m.attributes}
            all_translated_attributes.each do |translated_record|
              # Create a hash containing the translated column names and their values.
              translated_attribute_names.inject(fields_to_update={}) do |f, name|
                f.update({name.to_sym => translated_record[name.to_s]})
              end
    
              # Now, update the actual model's record with the hash.
              klass.update_all(fields_to_update, {:id => translated_record['id']})
            end
          end
        end
      end
    end
    
  3. 使用以下内容创建了迁移:

    class TranslateAndMigratePages < ActiveRecord::Migration
      def self.up
        Page.create_translation_table!({
          :title => :string,
          :custom_title => :string,
          :meta_keywords => :string,
          :meta_description => :text,
          :browser_title => :string
        })
    
        say_with_time('Migrating Page data to translation tables') do
          Page.move_data_to_translation_table
        end
      end
    
      def self.down
        say_with_time('Moving Page translated values into main table') do
          Page.move_data_to_model_table
        end
        Page.drop_translation_table!
      end
    end
    

从 Globalize 3 和 reinerycms 大量借用。

于 2011-05-12T21:28:30.557 回答