Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

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>

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.

like image 604
Alexander Trust Avatar asked Dec 13 '15 01:12

Alexander Trust


1 Answers

Is this what you want?

= f.select :parallax_id, options_for_select(@parallax.map {|p| [p.title, p.id, {'data-icon' => p.image }]})
like image 70
Hoang Phan Avatar answered Oct 25 '22 08:10

Hoang Phan