问题描述
我有:
form.input :duration, as: select, collection: {}
我需要:
<option value="" data-price="XXX"></option>
Rails 不支持选项标签的 HTML5 数据属性.Formtastic 建议为此创建一个辅助方法.
Rails does not support HTML5 data attributes for the option tag. Formtastic suggests to create a helper method for this.
Formtastic 自述文件描述如何扩展输入标签.但是,在 select_input.rb 中我找不到任何方法会影响 option 标签.那么,我该怎么做?
Formtastic readme describes how to extend input tags. However, in select_input.rb I can't find any method which would affect the option tag. So, how do I do this?
此外,我发现 enhanced_select gem 正好满足我的需求,但我无法使其与 formtastic 一起使用.
Also, I found enhanced_select gem which does exactly what I need, but I am not able to make it work with formtastic.
推荐答案
实际上 rails 确实支持向选项添加任何类型的 html 标签.通常你会:
Actually rails does support adding any kind of html tag to options. Usually you would have:
options_for_select( [['First', 1], ['Second', 2]] )
哪个会给你
<option value="1">First</option>
<option value="2">Second</option>
如果您为每个选项在数组中添加一个散列,散列键/值将作为 HTML 属性添加到选项中,例如
If you add a hash into the arrays for each option the hash keys/values will be added as HTML attribute to the option, e.g.
options_for_select( [['First', 1, {:'data-price' => 20}],
['Second', 2, {:'data-price' => 30}]] )
将产生所需的标签:
<option value="1" data-price="20">First</option>
<option value="2" data-price="30">Second</option>
这篇关于Rails Formtastic:添加“数据-"选项标签的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!