12

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.

Alexander Trust
  • 834
  • 7
  • 14

2 Answers2

20

Is this what you want?

= f.select :parallax_id, options_for_select(@parallax.map {|p| [p.title, p.id, {'data-icon' => p.image }]})
Hoang Phan
  • 2,146
  • 1
  • 15
  • 16
  • Thanks a lot. I wonder why it works with the `select` helper but not with the `collection_select` helper. I tried a command similar to yours with `collection_select` before asking the question but it did not provide me with this results. So now I just have to change my app's forms but that's okay. I'm glad that it works like this. It's more convenient as to output the options by hand with a `.each` loop. Thank you. :) – Alexander Trust Dec 13 '15 at 02:49
  • it works because it's a [documented](https://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select) feature: `You can optionally provide HTML attributes as the last element of the array.`. but i didn't know about it either. +1 hoang. – glasz Oct 17 '18 at 21:01
  • this helped me a lot, when trying to figure out how to disable only specific options. I didn't know about the 3rd parameter in the list (name, id, attributes) – Sam Dec 02 '21 at 00:09
0

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?.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    Welcome to Stack Overflow. Please explain your answer and do not just past a link (they can get obsolete). [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). – ChristianB Dec 31 '20 at 12:18
  • The post you have linked to answers a different question. The result the questioner is looking for is similar to ``. The other post generates ``. (The OP here wants `data-icon` values, but using `class` is easier to see in an example.) – Anita Graham Apr 07 '22 at 12:58