Ruby on Rails 翻译 ActiveRecord 模型属性
例子
globalizegem是为ActiveRecord模型添加翻译的绝佳解决方案。您可以安装它,将其添加到您的Gemfile:
gem 'globalize', '~> 5.0.0'
如果您正在使用,Rails5您还需要添加activemodel-serializers-xml
gem 'activemodel-serializers-xml'
模型翻译允许您翻译模型的属性值,例如:
class Post < ActiveRecord::Base translates :title, :text end I18n.locale = :en post.title # => Globalize rocks! I18n.locale = :he post.title # => גלובאלייז2 שולט!
在定义需要转换的模型属性后,您必须通过迁移创建转换表。globalize提供create_translation_table!和drop_translation_table!。
对于此迁移,您需要使用upanddown,而不是change。此外,为了成功运行此迁移,您必须首先在模型中定义已转换的属性,如上所示。以前Post模型的正确迁移是这样的:
class CreatePostsTranslationTable < ActiveRecord::Migration
def up
Post.create_translation_table! title: :string, text: :text
end
def down
Post.drop_translation_table!
end
end您还可以传递特定选项的选项,例如:
class CreatePostsTranslationTable < ActiveRecord::Migration
def up
Post.create_translation_table! title: :string,
text: { type: :text, null: false, default: "Default text" }
end
def down
Post.drop_translation_table!
end
end如果您需要的翻译列中已经有任何现有数据,您可以通过调整迁移轻松将其迁移到翻译表:
class CreatePostsTranslationTable < ActiveRecord::Migration
def up
Post.create_translation_table!({
title: :string,
text: :text
}, {
migrate_data: true
})
end
def down
Post.drop_translation_table! migrate_data: true
end
end确保在安全迁移所有数据后从父表中删除已翻译的列。要在数据迁移后自动从父表中删除翻译的列,请在迁移中添加选项remove_source_columns:
class CreatePostsTranslationTable < ActiveRecord::Migration
def up
Post.create_translation_table!({
title: :string,
text: :text
}, {
migrate_data: true,
remove_source_columns: true
})
end
def down
Post.drop_translation_table! migrate_data: true
end
end您还可以向先前创建的翻译表添加新字段:
class Post < ActiveRecord::Base
#请记住也要在此处添加您的属性。
translates :title, :text, :author
end
class AddAuthorToPost < ActiveRecord::Migration
def up
Post.add_translation_fields! author: :text
end
def down
remove_column :post_translations, :author
end
end