0

globalize3 gem 的 github 页面https://github.com/svenfuchs/globalize3清楚地概述了如何使用您想要多次翻译的字符串和文本属性来准备模型的迁移。例如:

 class CreatePosts < ActiveRecord::Migration
   def up
     create_table :posts do |t|
     t.timestamps
   end
   Post.create_translation_table! :title => :string, :text => :text
 end
 def down
   drop_table :posts
   Post.drop_translation_table!
 end
 end

如果我有某些不需要翻译的属性怎么办——例如保存 user_id 或其他整数值属性。我是否将它们写在下面作为 Post.create_translation_table 的一部分!声明,还是将它们留在 create_table :posts 部分的上方?

EG 哪个是正确的:

 def up
    create_table :posts do |t|
      #put it here as t.integer :user_id?
    end
    Post.create_translation_table! :title => string, :text => :text #user_id dec here?
 end

谢谢!

4

1 回答 1

2

快速回答:是的,您对待未翻译的属性就像对待任何其他 activerecord 模型中的属性一样,所以:

create_table :posts do |t|
  t.integer :user_id
end

是正确的。

所做的是create_translation_table创建一个名为 的单独post_translations,它将在其中存储已翻译属性的各个翻译以及特定翻译的语言环境和posts表中父记录的 id。

如果您在schema.rb运行迁移后查看,您将看到两个表,其中一个带有user_id(和时间戳,始终需要):

create_table "posts", :force => true do |t|
  t.integer  "user_id"
  t.datetime "created_at",                 :null => false
  t.datetime "updated_at",                 :null => false
end

以及另一个用于翻译属性翻译的表,该表是由您create_translation_table在迁移中调用创建的:

create_table "post_translations", :force => true do |t|
  t.integer  "post_id"
  t.string   "locale"
  t.string   "title"
  # any other translated attributes would appear here
  t.datetime "created_at",  :null => false
  t.datetime "updated_at",  :null => false
end

你可能会问,为什么 globalize3 会创建一个单独的表呢?为什么不将它们与父记录放在同一个表中(例如,以表格title_en等形式title_es)?还有其他翻译 gem 可以做到这一点,例如traco。但问题是,如果您将翻译放在父记录中,那么您必须事先指定您将支持的语言环境,因为您需要为每个语言环境中的属性创建列。如果添加新的语言环境,则必须迁移数据库以支持它们。

另一方面,使用 globalize3 解决方案,您不必事先决定要支持哪些语言环境,因为翻译表中的每条已翻译记录都附加了一个语言环境——您不会在任何地方“硬编码”支持的语言环境。这是处理问题的一种非常优雅的方式,并且是 globalize3 流行的基础,但一开始可能会有点混乱,因为 gem 必须做一些诡计才能使它看起来像属性附加到模型 ( Post)而它们实际上是附加到另一个类的,Post::Translation.

无论如何,这比你要求的要多,但是有用的东西要知道。

于 2012-09-17T22:55:22.273 回答