Rails 4 Active Record枚举很棒,但是使用i18n进行翻译的正确模式是什么?
Rails 4 Active Record枚举很棒,但是使用i18n进行翻译的正确模式是什么?
Answers:
从Rails 5开始,所有模型都将从继承ApplicationRecord
。
class User < ApplicationRecord
enum status: [:active, :pending, :archived]
end
我使用此超类来实现用于翻译枚举的通用解决方案:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.human_enum_name(enum_name, enum_value)
I18n.t("activerecord.attributes.#{model_name.i18n_key}.#{enum_name.to_s.pluralize}.#{enum_value}")
end
end
然后在我的.yml
文件中添加翻译:
en:
activerecord:
attributes:
user:
statuses:
active: "Active"
pending: "Pending"
archived: "Archived"
最后,要获得翻译,我使用:
User.human_enum_name(:status, :pending)
=> "Pending"
<%= f.select :status, User.statuses.keys.collect { |status| [User.human_enum_name(:status, status), status] } %>
。
human_enum_name(@user, :status)
self.human_enum_collection(enum_name)
。代码应为 send(enum_name.to_s.pluralize).keys.collect { |val| [human_enum_name(enum_name, val), val] }
这是一个视图:
select_tag :gender, options_for_select(Profile.gender_attributes_for_select)
这是一个模型(您可以将此代码实际移到帮助器或装饰器中)
class Profile < ActiveRecord::Base
enum gender: {male: 1, female: 2, trans: 3}
# @return [Array<Array>]
def self.gender_attributes_for_select
genders.map do |gender, _|
[I18n.t("activerecord.attributes.#{model_name.i18n_key}.genders.#{gender}"), gender]
end
end
end
这是语言环境文件:
en:
activerecord:
attributes:
profile:
genders:
male: Male
female: Female
trans: Trans
.human_attribute_name('genders.male')
不起作用
为了使国际化与任何其他属性相似,我遵循嵌套属性的方法,如您在此处看到的。
如果您上课User
:
class User < ActiveRecord::Base
enum role: [ :teacher, :coordinator ]
end
和yml
这样的:
pt-BR:
activerecord:
attributes:
user/role: # You need to nest the values under model_name/attribute_name
coordinator: Coordenador
teacher: Professor
您可以使用:
User.human_attribute_name("role.#{@user.role}")
activerecord.attributes.<fieldname>
是在label
翻译形式的帮手
role
密钥。您可以嵌套coordinator
并teacher
直接位于user
。
模型:
enum stage: { starting: 1, course: 2, ending: 3 }
def self.i18n_stages(hash = {})
stages.keys.each { |key| hash[I18n.t("checkpoint_stages.#{key}")] = key }
hash
end
语言环境:
checkpoint_stages:
starting: Saída
course: Percurso
ending: Chegada
并在视图(.slim)上:
= f.input_field :stage, collection: Checkpoint.i18n_stages, as: :radio_buttons
尝试将TranslateEnum gem用于这些目的
class Post < ActiveRecord::Base
enum status: { published: 0, archive: 1 }
translate_enum :status
end
Post.translated_status(:published)
Post.translated_statuses
@post = Post.new(status: :published)
@post.translated_status
我为此创造了一颗宝石。
http://rubygems.org/gems/translated_attribute_value
添加到您的gemfile:
gem 'translated_attribute_value'
如果您有用户的状态字段:
pt-BR:
activerecord:
attributes:
user:
status_translation:
value1: 'Translation for value1'
value2: 'Translation for value2'
在您看来,您可以这样调用:
user.status_translated
它适用于活动记录,mongoid或具有getter / setter的任何其他类:
结合Repolês和Aliaksandr的答案,对于Rails 5,我们可以构建2种方法,使您可以转换枚举属性中的单个值或值的集合。
在.yml
文件中设置翻译:
en:
activerecord:
attributes:
user:
statuses:
active: "Active"
pending: "Pending"
archived: "Archived"
在ApplicationRecord
所有模型都继承自的类中,我们定义了一个方法,该方法处理单个值的转换,而另一个方法则通过调用它来处理数组:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.translate_enum_name(enum_name, enum_value)
I18n.t("activerecord.attributes.#{model_name.i18n_key}.#{enum_name.to_s.pluralize}.#{enum_value}")
end
def self.translate_enum_collection(enum_name)
enum_values = self.send(enum_name.to_s.pluralize).keys
enum_values.map do |enum_value|
self.translate_enum_name enum_name, enum_value
end
end
end
在我们看来,我们可以转换单个值:
<p>User Status: <%= User.translate_enum_name :status, @user.status %></p>
或整个枚举值集合:
<%= f.select(:status, User.translate_enum_collection :status) %>
t_enum
这是我使用的辅助方法。
<%= t_enum(@user, :status) %>
enum_helper.rb:
module EnumHelper
def t_enum(inst, enum)
value = inst.send(enum);
t_enum_class(inst.class, enum, value)
end
def t_enum_class(klass, enum, value)
unless value.blank?
I18n.t("activerecord.enums.#{klass.to_s.demodulize.underscore}.#{enum}.#{value}")
end
end
end
user.rb:
class User < ActiveRecord::Base
enum status: [:active, :pending, :archived]
end
en.yml:
en:
activerecord:
enums:
user:
status:
active: "Active"
pending: "Pending..."
archived: "Archived"
该模型:
class User < ActiveRecord::Base
enum role: [:master, :apprentice]
end
语言环境文件:
en:
activerecord:
attributes:
user:
master: Master
apprentice: Apprentice
用法:
User.human_attribute_name(:master) # => Master
User.human_attribute_name(:apprentice) # => Apprentice
@user.role
,因为那是主要问题。
我更喜欢application_helper中的简单助手
def translate_enum(object, enum_name)
I18n.t("activerecord.attributes.#{object.model_name.i18n_key}.#{enum_name.to_s.pluralize}.#{object.send(enum_name)}")
end
然后在我的YML文件中:
fr:
activerecord:
attributes:
my_model:
my_enum_plural:
pending: "En cours"
accepted: "Accepté"
refused: "Refusé"
还有另一种方式,我发现使用模型中的关注点会更方便
关心 :
module EnumTranslation
extend ActiveSupport::Concern
def t_enum(enum)
I18n.t "activerecord.attributes.#{self.class.name.underscore}.enums.#{enum}.#{self.send(enum)}"
end
end
YML:
fr:
activerecord:
attributes:
campaign:
title: Titre
short_description: Description courte
enums:
status:
failed: "Echec"
查看:
<% @campaigns.each do |c| %>
<%= c.t_enum("status") %>
<% end %>
不要忘记在模型中添加关注点:
class Campaign < ActiveRecord::Base
include EnumTranslation
enum status: [:designed, :created, :active, :failed, :success]
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.enum(definitions)
defind_i18n_text(definitions) if definitions.delete(:_human)
super(definitions)
end
def self.defind_i18n_text(definitions)
scope = i18n_scope
definitions.each do |name, values|
next if name.to_s.start_with?('_')
define_singleton_method("human_#{name.to_s.tableize}") do
p values
values.map { |key, _value| [key, I18n.t("#{scope}.enums.#{model_name.i18n_key}.#{name}.#{key}")] }.to_h
end
define_method("human_#{name}") do
I18n.t("#{scope}.enums.#{model_name.i18n_key}.#{name}.#{send(name)}")
end
end
end
end
en:
activerecord:
enums:
mymodel:
my_somethings:
my_enum_value: "My enum Value!"
enum status: [:unread, :down], _human: true
{locale}.activerecord.attributes.{model}.{attribute}
并写了一个t_enum(model, enum, value)
辅助方法,因此枚举翻译将与标签翻译相邻