rails 模型的国际化(翻译)数组值如何?
How can internationalized(translated) array's value of rails model?
此部分存在于模型中,我们将其用于表单提交。
GENDER_TYPES = %w[Male Female Other]
我不确定这是否适合你,但我在这种情况下所做的是使用 (Rails enum)。在您的模型中:
class MyModel < ApplicationRecord
enum gender: [:male, :female, :other]
end
我的申请记录class:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.enum_t(enum_name, enum_value)
I18n.t("activerecord.attributes.#{model_name.i18n_key}.#{enum_name.to_s.pluralize}.#{enum_value}")
end
end
在我的 en.yml:
en:
activerecord:
attributes:
my_model:
genders:
male: Male
female: Female
other: Other
我认为创建select:
f.select :gender, MyModel.genders.keys.collect { |gender| [MyModel.enum_t(:gender, gender), gender] }
或显示动作:
= MyModel.enum_t(:gender, my_model.gender)
此部分存在于模型中,我们将其用于表单提交。
GENDER_TYPES = %w[Male Female Other]
我不确定这是否适合你,但我在这种情况下所做的是使用 (Rails enum)。在您的模型中:
class MyModel < ApplicationRecord
enum gender: [:male, :female, :other]
end
我的申请记录class:
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.enum_t(enum_name, enum_value)
I18n.t("activerecord.attributes.#{model_name.i18n_key}.#{enum_name.to_s.pluralize}.#{enum_value}")
end
end
在我的 en.yml:
en:
activerecord:
attributes:
my_model:
genders:
male: Male
female: Female
other: Other
我认为创建select:
f.select :gender, MyModel.genders.keys.collect { |gender| [MyModel.enum_t(:gender, gender), gender] }
或显示动作:
= MyModel.enum_t(:gender, my_model.gender)