[英]Rails i18n - How to translate model in fields_for that has_one inherited model
[英]Rails i18n - How to translate enum of a model
我有以下型號:
class Person < ActiveRecord::Base
enum gender: [:female, :male]
...
end
然后我將性別選擇添加到其表單中,如下所示:
<%= form_for ([@person]) do |f| %>
...
<div class="form-group">
<%= f.collection_radio_buttons :gender, Person.genders, :first, :first %>
</div>
...
<% end %>
但不是將常量顯示為字符串,而是將其翻譯為葡萄牙語。
我已經嘗試將它添加到人們的pt.yml文件中但是沒有用。
pt:
activerecord:
attributes:
female: Feminino
male: Mascúlino
我知道這個問題非常類似於如何使用i18n和Rails 4枚舉,但這個問題已經標記為已回答,我正在尋找更好,更簡單的解決方案......
感謝您抽出寶貴時間幫助我:)
閱讀如何使用i18n與Rails 4枚舉答案更仔細我來到這個解決方案:
yml
文件應如下所示:
pt:
activerecord:
attributes:
person/gender:
female: Feminino
male: Mascúlino
enum
的方法,因為沒有任何方法可以一次翻譯整個enum
。 Rails只有翻譯給定鍵的值的方法,即People.human_attribute_name(“gender.female”)。 好的,我們將創建一個新方法,但我們應該把它放在哪里?
我認為Helpers
是放置它的最佳位置,因為我正在更改枚舉值以便輕松地將它們附加到form collection
,盡管大多數答案都建議將它放在Models
。
現在我的person_helper.rb
看起來像這樣:
def human_attribute_genders
Hash[Person.genders.map { |k,v| [k, Person.human_attribute_name("gender.#{k}")] }]
end
我的view
:
<%= f.collection_radio_buttons :gender, human_attribute_genders, :first, :second %>
很簡單,它工作得很好!
如果有人有任何改進我的解決方案的建議,我很樂意聽到你的意見:)
例如,我可以像這樣將方法提取到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
但它需要在view
傳遞很多參數......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.