我有一个表单 Select 语句,如下所示:

= f.select :country_id, @countries.map{ |c| [c.name, c.id] }

这导致了以下代码:

...
<option value="1">Andorra</option>
<option value="2">Argentina</option>
...

但我想在我的选项中添加一个自定义HTML属性,如下所示:

...
<option value="1" currency_code="XXX">Andorra</option>
<option value="2" currency_code="YYY">Argentina</option>
...

推荐答案

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

Ruby-on-rails相关问答推荐

使用RubyZip处理大型压缩文件:65535个文件的限制

`heroku Open`和`heroku run rake db:Migrate`不工作(";没有这样的文件或目录";)

Rails 7,返回具有两个单独条件的活动记录关联,一个在父级,一个在子级

错误 NoMethodError:ActionView::Base:Class 的未定义方法 `debug_rjs='

Rails Migration将字符串转换为整数?

ActiveRecord 回调列表

如何配置设计以使用自定义邮箱布局?

查找日期时间与今天匹配的记录 - Ruby on Rails

如何获取 Ruby on Rails 生成的表单元素 id 以供 JavaScript 参考?

水豚 click_link 与 :href 匹配

添加自定义字段/列以使用 Rails 4 进行设计

是否可以在 Rails 中否定范围?

如何在 Rails 1.2.3 中使复选框默认为选中?

如何获取包含表的列名的数组

Django 还是 Ruby-On-Rails?

如何打印出范围之间的随机数?

如何覆盖:在 has_many 中定义的顺序

Vagrant上的Rails 4.2服务器端口转发不起作用

从模型中获取验证

为什么 Mac OS X 带有 ruby​​/rails?