How to Send Multiple Select Values as an Array in Rails Params?

66 Views Asked by At

I have a complex form in a Rails application where I'm using multiple instances of a template. Each template contains a dropdown for product variations. When the form is submitted, I want to send the selected values of each of these dropdowns as an array within the params.

Here is a simplified example of my form:

<div class="nested-form-wrapper">
  <!-- Other form fields -->
  <div class="variatios_form_container"></div>

  <template id="variationsFormTemplate">
    <div data-controller="variations">
      <select id="variation_select" data-action="change->variations#change">
        <!-- Options -->
      </select>
      <div>
        <%= f.label :variation_options, 'Select an option' %>
        <%= f.select :variation_options, [], {}, {data: {variations_target: "optionsSelect"}} %>
      </div>
    </div>
  </template>
</div>

In my controller, I want to handle these multiple variation_options values. Ideally, they would come in as an array in params, something like:

params[:product_stock][:variation_options] = [val1, val2, val3, ...]

How can I structure my form or controller to accomplish this?

What I've Tried:

Setting Array in Select Name: Tried naming the select as variation_options[] to make it an array, but received a NoMethodError.

<%= f.select 'variation_options[]', [], {}, {data: {variations_target: "optionsSelect"}} %>

Assigning Unique IDs: I tried to assign unique IDs to each select element by incrementing a counter, but this doesn't solve the issue of sending them as an array in params.

1

There are 1 best solutions below

1
David On

Does setting multiple: true on the select do the trick?

<%= f.select :variation_options, [], {multiple: true}, {data: {variations_target: "optionsSelect"}} %>