简体   繁体   English

Rails:如何在 collection_select 中添加自定义数据属性

[英]Rails: How to add custom data-attributes in collection_select

I am working on a solution to add custom data-attributes to option-tags with the collection_select form helper in Rails.我正在研究使用 Rails 中的collection_select表单助手将自定义数据属性添加到选项标签的解决方案。

I studied some posts at stackoverflow and did a lot of trial and error after consulting some API documentation.我研究了 stackoverflow 上的一些帖子,并在查阅了一些 API 文档后进行了大量的反复试验。 I am nearly there but sadly my solution only adds attributes to the select -tag not to the option -tags.我快到了,但遗憾的是我的解决方案只将属性添加到select -tag 而不是option -tags。

This way I am populating the html-options-hash (6th position):这样我就填充了 html-options-hash(第 6 位):

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

But I want the option to get the data-icon attribute.但我想要获取data-icon属性的选项。 When I switch positions and add my data-icon to the options-hash (5th position) nothing is output.当我切换位置并将我的数据图标添加到选项哈希(第 5 个位置)时,没有任何输出。

这是你想要的吗?

= f.select :parallax_id, options_for_select(@parallax.map {|p| [p.title, p.id, {'data-icon' => p.image }]})

Just FYI I was looking at this matter, found the more fitting solution here: How do I set the HTML options for collection_select in Rails?仅供参考,我正在研究这个问题,在这里找到了更合适的解决方案: How do I set the HTML options for collection_select in Rails? . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM