0

globalize/globalize中,我想回退到其他列。样品来源。

class CreatePosts < ActiveRecord::Migration
  def up
    create_table :posts do |t|
      t.string :foo, null: false

      t.timestamps null: false
    end
    Post.create_translation_table! hoge: :string
  end
end

class Post < ActiveRecord::Base
  # this not work. but I want to like this.
  translates :hoge, :fallbacks_for_empty_translations => :foo
end

虽然看起来像是对 columnhoge和的双重管理foo,但我计划在 column为空hoge的情况下显示 column 的内容。foo您可以编辑开源的内容globalize

4

1 回答 1

0

正如 globalize 文档中所指定的,您不需要将可翻译列添加到表迁移中,而是将其作为创建翻译表的参数传递

class CreatePosts < ActiveRecord::Migration
  def up
    create_table :posts do |t|
      # no foo column specified here
      t.timestamps null: false
    end
  Post.create_translation_table! foo: :string
  end
end

class Post < ActiveRecord::Base
  translates :foo, :fallbacks_for_empty_translations => true
end

这不会为每种语言创建单独的列,而是在翻译表中为与主模型表中的每个条目相关联的每种语言创建一个新条目。

如果您已正确设置

config.i18n.fallbacks = true

并设置:en为默认语言,每当缺少特定于语言环境的值时获取 foo 字段的值将默认为英语值。例如,给定两个带有数据的帖子 (post1和)post2

[#<Post::Translation id: 1, post_id: 1, locale: "en", foo: 'Italy'>,
  #<Post::Translation id: 2, post_id: 1, locale: "jp", foo: 'Hetalia'>,
  #<Post::Translation id: 3, post_id: 2, locale: "en", foo: 'Finland'>,
  #<Post::Translation id: 4, post_id: 2, locale: "jp", foo: ''>]

如果你的语言环境是日语,你会得到

post1.foo # => 'Hetalia'
post2.foo # => 'Finland'
于 2015-11-26T11:47:24.130 回答