[英]Rails i18n - How to translate enum of a model
I've got the following model: 我有以下型号:
class Person < ActiveRecord::Base
enum gender: [:female, :male]
...
end
Then I added the selection of the gender to its form, like this: 然后我将性别选择添加到其表单中,如下所示:
<%= form_for ([@person]) do |f| %>
...
<div class="form-group">
<%= f.collection_radio_buttons :gender, Person.genders, :first, :first %>
</div>
...
<% end %>
But instead of displaying the constant as a string I want to translate it to Portuguese. 但不是将常量显示为字符串,而是将其翻译为葡萄牙语。
I already tried to add it to the pt.yml file under people but didn't work. 我已经尝试将它添加到人们的pt.yml文件中但是没有用。
pt:
activerecord:
attributes:
female: Feminino
male: Mascúlino
I know this question is very similar to How to use i18n with Rails 4 enums but that question is already marked as answered and I'm searching for a better and simpler solution... 我知道这个问题非常类似于如何使用i18n和Rails 4枚举,但这个问题已经标记为已回答,我正在寻找更好,更简单的解决方案......
Thank you for taking your time to help me :) 感谢您抽出宝贵时间帮助我:)
After reading How to use i18n with Rails 4 enums answers more carefully I came to this solution: 阅读如何使用i18n与Rails 4枚举答案更仔细我来到这个解决方案:
the yml
file should look like this: yml
文件应如下所示:
pt:
activerecord:
attributes:
person/gender:
female: Feminino
male: Mascúlino
enum
since there isn't any method capable of translating an entire enum
at once. 我们需要创建一个返回翻译enum
的方法,因为没有任何方法可以一次翻译整个enum
。 Rails just has the method to translate a value given a key, ie People.human_attribute_name("gender.female"). Rails只有翻译给定键的值的方法,即People.human_attribute_name(“gender.female”)。 Ok, we'll create a new method but where should we put it? 好的,我们将创建一个新方法,但我们应该把它放在哪里?
I think Helpers
are the best place to put it because I'm changing the enum values in order to easily attach them to the form collection
, although most of the answers suggested to put it in the Models
. 我认为Helpers
是放置它的最佳位置,因为我正在更改枚举值以便轻松地将它们附加到form collection
,尽管大多数答案都建议将它放在Models
。
Now my person_helper.rb
looks like this: 现在我的person_helper.rb
看起来像这样:
def human_attribute_genders
Hash[Person.genders.map { |k,v| [k, Person.human_attribute_name("gender.#{k}")] }]
end
And my view
: 我的view
:
<%= f.collection_radio_buttons :gender, human_attribute_genders, :first, :second %>
Pretty simple and it works just fine! 很简单,它工作得很好!
If anyone has any suggestion to improve my solution I would be happy to hear it from you :) 如果有人有任何改进我的解决方案的建议,我很乐意听到你的意见:)
For example, I could extract the method to application_helper.rb
like this: 例如,我可以像这样将方法提取到application_helper.rb
:
def human_attribute_enum(model_name, enum_attr, attr_name)
Hash[enum_attr.map { |k,v| [k, I18n.t("activerecord.attributes.#{model_name}/#{attr_name}.#{k}")] }]
end
But it'd require passing a lot of parameters in the view
... 但它需要在view
传递很多参数......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.