In my Rails 7 app, I am using Stimulus and need to add data attributes to a form select to link it to a JavaScript controller. I am also trying to format the field (not the options) with a class.
Here is the form select element:
<%= f.select(:repeat, Batch.repeats, {class: "class_name"}, { data: { batch_repeat_target: "input", action: "change->batch-repeat#toggle" }}) %>
The above code results in the data attributes being applied to the select field, but leaving the class out.
I also tried to flip the class and the data attributes, as follows:
<%= f.select(:repeat, Batch.repeats, { data: { batch_repeat_target: "input", action: "change->batch-repeat#toggle" }}, { class: "class_name" }) %>
The result was the opposite of the first approach: this time, the field was styled per the class, but the data attributes were not associated with the select element.
Per this question, I became aware that:
selecthelper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class tohtml_options.
From there, I thought that I needed to include both the class and the data attributes in the first option hash, and leave the second one empty, along the following lines:
<%= f.select(:repeat, Batch.repeats, { { class: "class_name" }, { data: { batch_repeat_target: "input", action: "change->batch-repeat#toggle" }}}, {}) %>
However, the above revised code resulted in an ActionView::SyntaxErrorInTemplate in BatchesController#new error.
In yet another attempt, I tried to shuffle things around, leaving the first option hash empty and including both the class and the data attributes in the second one, as follows:
<%= f.select(:repeat, Batch.repeats, {}, { { class: "class_name" }, { data: { batch_repeat_target: "input", action: "change->batch-repeat#toggle" }}}) %>
That revision also resulted in an ActionView::SyntaxErrorInTemplate in BatchesController#new error.
The question referenced above is more than 11 years old and: is there a different convention now, particularly in Rails 7, with regards to form select elements? How can I both include a class and data attributes here?