Rails 4 Active Record Enums很棒,但是用i18n进行翻译的正确模式是什么?
我也没有找到任何特定的模式,所以我只是添加了:
en:
user_status:
active: Active
pending: Pending...
archived: Archived
尝试enum_help宝石。从其描述:
这里有我使用的t_enum
辅助方法。
模型:
我更喜欢application_helper中的简单帮助器
还有另一种方法,使用模型中的关注点,我发现它更方便
您可以简单地添加一个助手:
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
从Rails 5开始,所有模型都将从ApplicationRecord
继承。
这里是视图:
为了使国际化与任何其他属性相似,我遵循嵌套属性的方式,如您所见here。
型号:
详细阐述user3647358的答案,您可以非常轻松地完成转换属性名称时所惯用的操作。
尝试将TranslateEnum宝石用于这些目的
我为此创建了一个宝石。
结合Repolês和Aliaksandr的答案,对于Rails 5,我们可以构建2个方法,使您可以转换枚举属性中的单个值或值的集合。