Created
August 24, 2018 13:58
-
-
Save sadiqmmm/9246e88e777cf9c209094178218129c1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Rails CAN add custom attributes to select options, using the existing options_for_select helper. You almost had it right in the code in your question. Using html5 data-attributes: | |
<%= f.select :country_id, options_for_select(@countries.map{ |c| [c.name, c.id, {'data-currency_code'=>c.currency_code}] }) %> | |
Adding an initial selection: | |
<%= f.select :country_id, options_for_select(@countries.map{ |c| [c.name, c.id, {'data-currency_code'=>c.currency_code}] }, selected_key = f.object.country_id) %> | |
If you need grouped options, you can use the grouped_options_for_select helper, like this (if @continents is an array of continent objects, each having a countries method): | |
<%= f.select :country_id, grouped_options_for_select(@continents.map{ |group| [group.name, group.countries.map{ |c| [c.name, c.id, {'data-currency_code'=>c.currency_code}] } ] }, selected_key = f.object.country_id) %> | |
Credit should go to paul @ pogodan who posted about finding this not in the docs, but by reading the rails source. http://pogodan.com/blog/2011/02/24/custom-html-attributes-in-options-for-select |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment