【问题标题】:globalize3 translating gem: What do I do about attributes that don't need translation (in writing migration)?globalize3 翻译 gem:我如何处理不需要翻译的属性(在编写迁移时)?
【发布时间】:2012-09-17 22:28:40
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 translation globalize3


    【解决方案1】:

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

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

    是正确的。

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

    如果您在运行迁移后查看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_entitle_es 等)?还有其他翻译宝石可以做到这一点,例如traco。但问题是,如果您将翻译放在父记录中,那么您必须事先指定您将支持哪些语言环境,因为您需要为每个语言环境中的属性创建列。如果添加新的语言环境,则必须迁移数据库以支持它们。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 1970-01-01
      • 2011-05-19
      • 1970-01-01
      • 2020-04-01
      • 2011-10-19
      • 1970-01-01
      相关资源
      最近更新 更多