Rails可以使用现有的选项来添加自定义属性来 Select 选项.你的问题中的代码几乎是对的.使用html5数据属性:
<%= f.select :country_id, options_for_select(
@countries.map{ |c| [c.name, c.id, {'data-currency_code'=>c.currency_code}] }) %>
添加初始 Select :
<%= f.select :country_id, options_for_select(
@countries.map{ |c| [c.name, c.id, {'data-currency_code'=>c.currency_code}] },
selected_key = f.object.country_id) %>
如果需要分组选项,您可以使用分组的_选项_for _selecthelper,如下图所示(如果@continents是一组大陆对象,每个对象都有一个国家方法):
<%= f.select :country_id, grouped_options_for_select(
@continents.map{ |group| [group.name, group.countries.
map{ |c| [c.name, c.id, {'data-currency_code'=>c.currency_code}] } ] },
selected_key = f.object.country_id) %>
这应该归功于paul@pogodan,他发布了关于在文件中找到这一点的帖子,而是通过阅读rails源代码.https://web.archive.org/web/20130128223827/http://www.pogodan.com/blog/2011/02/24/custom-html-attributes-in-options-for-select