Search code examples
ruby-on-railsformtastic

Rails Formtastic: adding "data-" field to option tag


I have:

form.input :duration, as: select, collection: {}

I need:

<option value="" data-price="XXX"></option>

Rails does not support HTML5 data attributes for the option tag. Formtastic suggests to create a helper method for this.

Formtastic readme describes how to extend input tags. However, in select_input.rb I can't find any method which would affect the option tag. So, how do I do this?

Also, I found enhanced_select gem which does exactly what I need, but I am not able to make it work with formtastic.


Solution

  • Actually rails does support adding any kind of html tag to options. Usually you would have:

    options_for_select( [['First', 1], ['Second', 2]] )
    

    which would give you

    <option value="1">First</option>
    <option value="2">Second</option>
    

    If you add a hash into the arrays for each option the hash keys/values will be added as HTML attribute to the option, e.g.

    options_for_select( [['First', 1, {:'data-price' => 20}],
                         ['Second', 2, {:'data-price' => 30}]] )
    

    will produce the required tags:

    <option value="1" data-price="20">First</option>
    <option value="2" data-price="30">Second</option>