ruby on rails f.select 具有自定义属性的选项 [英] ruby on rails f.select options with custom attributes

查看:29
本文介绍了ruby on rails f.select 具有自定义属性的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a form select statement, like this:

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

产生此代码的结果:

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

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

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 可以使用现有的 options_for_select 帮助程序添加自定义属性以选择选项.您在问题中的代码中几乎是正确的.使用 html5 数据属性:

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}] }) %>

添加初始选择:

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

如果你需要分组选项,你可以使用 grouped_options_for_select 助手,像这样(如果@continents 是一个大陆对象数组,每个对象都有一个 countries 方法):

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

应归功于 paul @ pogodan,他发布了有关不是在文档中而是通过阅读 rails 源代码找到的信息.https://web.archive.org/web/20130128223827/http://www.pogodan.com/blog/2011/02/24/custom-html-attributes-in-options-for-选择

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 f.select 具有自定义属性的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆