Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails simple_form element with data-... attributes for stimulus?

I am trying to hook up a stimulus controller to a form element which is inside a form generated by the simple form gem. Whatever I do - the corresponding "data-controller" attribute doesn't appear in the final rendered page (and hence, the controller won't react)...

Here's the code in question:

<%= simple_form_for book do |f| %>
  <%= render 'shared/form_errors', form: f %>
  ...
  <%= f.association :book_format, label: false, 'data-controller': 'book-format-select' %>
  ...
< % end %>

I also tried

<%= f.association :book_format, label: false, data_controller: 'book-format-select' %>

and

<%= f.association :book_format, label: false, html: {data-controller: 'book-format-select' } %>

None of that works - the output is always the same:

<select class="select required" name="book[book_format_id]" id="book_book_format_id">

Not sure what I am doing wrong?

like image 326
tkhobbes Avatar asked Oct 24 '25 10:10

tkhobbes


1 Answers

You need to use input_html key

It is also possible to pass any html attribute straight to the input, by using the :input_html option

<%= f.association :book_format, label: false, input_html: { data: { controller: 'book-format-select' } } %>
like image 100
mechnicov Avatar answered Oct 27 '25 00:10

mechnicov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!