I have a form select statement, like this:

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

Which results in this code:

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

But I want to add a custom HTML attribute to my options, like this:

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

推荐答案

Rails CAN add custom attributes to select options, using the existing options_for_select helper. You almost had it right in the code in your question. Using html5 data-attributes:

<%= f.select :country_id, options_for_select(
    @countries.map{ |c| [c.name, c.id, {'data-currency_code'=>c.currency_code}] }) %>

Adding an initial selection:

<%= 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) %>

If you need grouped options, you can use the grouped_options_for_select helper, like this (if @continents is an array of continent objects, each having a countries method):

<%= 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) %>

Credit should go to paul @ pogodan who posted about finding this not in the docs, but by reading the rails source. https://web.archive.org/web/20130128223827/http://www.pogodan.com/blog/2011/02/24/custom-html-attributes-in-options-for-select

Ruby-on-rails相关问答推荐

Rails turbo流只更新页面上的一个元素

链轮轨道V4链接到外部Ruby 的 list 文件

Rails 7中的Turbo流

合成轨道布局

Rails 5.1.7:Sprockets::Rails::Helper::AssetNotFound

Grape api (rails) - 未初始化常量 Endpoints::TodoAPI (NameError)

如何使用 RSpec 和 Devise/CanCan 进行集成测试?

如何在我的 rails 应用程序中测试 ActiveRecord::RecordNotFound?

基于 2 列定义唯一主键

价格字段的字符串、小数或浮点数据类型?

如何在我的 Gemfile 中找到未使用的Ruby

设计自定义路由和登录页面

如何在 Rails ActiveRecord 中指定日期小于今天的条件

格式化日期对象以显示人类可读的日期

验证一个对象是否有一个或多个关联对象

Heroku Postgres 错误:PGError:错误:关系组织不存在(ActiveRecord::StatementInvalid)

使用 ruby​​ on rails 活动记录插入多条记录

如何在 Rails 中设置路由的默认格式?

ActiveRecord 何时会保存关联?

如何删除特殊字符?