简体   繁体   中英

Rails: How to do i18n on a dropdown menu in simple_form

I have a simple_form that has a dropdown menu with a collection of options. I wish to have the options saved as integers, but the text shown in the dropdown as a string based on the locale. As follows:

<option value="1">Option 1</option>
<option value="2">Option 2</option>

I currently have the options defined as class methods in MyModel , as follows:

def self.options
 [['Option 1', 1], ['Option 2', 2]]
end

Without i18n I had the following working:

f.input :dropdown, collection: MyModel::boolean, include_blank: false

Adding the locales, I tried

f.input :dropdown, collection: t(MyModel::boolean, scope: 'simple_form'), include_blank: false

But this raises an error:

translation missing: en.simple_form.Option 1.1

It looks as if it looks for both the array key and value in the translation.

Any suggestions how to make i18n work for the collection?

由于simpleform集合接受proc,因此您可以在label_method上调用一个块,该块将根据需要格式化字符串,这可能是您要查找的内容:

f.input :dropdown, collection: MyModel::boolean, include_blank: false, :label_method => lambda { |item| t(item.last) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM