0

I've added hstore_translate to a Rails4 project with existing data.

class Product < ActiveRecord::Base
  translates :subtitle, :description
end

config.i18n.fallbacks = true

class AddTranslationColumnsToProducts < ActiveRecord::Migration
  def change
    add_column :products, :subtitle_translations, :hstore
    add_column :products, :description_translations,  :hstore
  end
end

How can I access my old subtitle and description fields? Because now Post.subtitle and Post.description always nil. Fallback doesn't work or I need migrate data first?

upd:

This migration solves problem.

class MigrateExistingDataToTranslations < ActiveRecord::Migration
  def change
    execute "UPDATE products p SET subtitle_translations=hstore('en',(select subtitle from products where id = p.id));"
    execute "UPDATE products p SET description_translations=hstore('en', (select description from products where id = p.id));"
  end
end
4

1 回答 1

1

hstore_translate定义了读取各种翻译的方法。

定义translates :subtitle, :description时,方法subtitle&description被创建,得到合适的翻译。因此,在调用时Product.subtitle,它不是获取列及其数据,而是调用该方法。

要临时访问数据,您应该注释掉hstore_translate设置

class Product < ActiveRecord::Base
  # translates :subtitle, :description
end

然后在再次取消注释之前将您的数据合并到新列。

于 2015-03-23T11:44:22.857 回答