Search code examples
ruby-on-railssimple-form

How do I add HTML attributes to select options with Simple Form Rails?


I need to add a custom HTML attribute to each option for a select control. I'm using simple_form in Rails. Does anyone know how to do this? The attribute will be consumed by client-side JS.

For instance, I want to do something like this:

<%= f.input :group, collection: @groups, option_html: { data-type: lambda { |g| g[2] } } %>

Which would produce (simplified):

<select>
    <option value="1" data-type="primary">First Group</option>
    <option value="2" data-type="secondary">Second Group</option>
    <option value="3" data-type="secondary">Third Group</option>
</select>

Where @groups might look like this:

[
    ['First Group', 1, 'primary'],
    ['Second Group', 2, 'secondary'],
    ['Third Group', 3, 'secondary']
]

Hoping to avoid having to make a custom control/wrapper. Thanks!


Solution

  • This seems to be the correct way of doing this:

    Rails Simple Form custom association select field