Rails:如何在collection_select中添加自定义数据属性 [英] Rails: How to add custom data-attributes in collection_select
问题描述
我正在使用Rails中的 collection_select
表单助手将自定义数据属性添加到选项标签中。
I am working on a solution to add custom data-attributes to option-tags with the collection_select
form helper in Rails.
我学习了一些在stackoverflow上的帖子,并在查阅了一些API文档后做了大量的试验和错误。我几乎在那里,但可悲的是我的解决方案只添加属性到选择
-tag而不是选项
-tags。
I studied some posts at stackoverflow and did a lot of trial and error after consulting some API documentation. I am nearly there but sadly my solution only adds attributes to the select
-tag not to the option
-tags.
通过这种方式,我填充html-options-hash(第6位):
This way I am populating the html-options-hash (6th position):
<%= f.collection_select(:parallax_id, @parallax.all, :id, :title, {}, { :"data-icon" => @parallax.map{ |p| "#{p.image}"}} ) %>
这会产生一个如下所示的选择标记:
This results in a select tag like:
<select data-icon="/uploads/image/image/4/169_strecken-ausgang.jpg" name="game[parallax_id]" id="game_parallax_id">...</select>
但我想要获取数据图标
属性。当我切换位置并将数据图标添加到options-hash(第5个位置)时,不会输出任何内容。
But I want the option to get the data-icon
attribute. When I switch positions and add my data-icon to the options-hash (5th position) nothing is output.
推荐答案
你想要什么?
= f.select :parallax_id, options_for_select(@parallax.map {|p| [p.title, p.id, {'data-icon' => p.image }]})
这篇关于Rails:如何在collection_select中添加自定义数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!