arraysruby-on-railsformbuilderform-with

Return an array using `form_with`?


In my view, I have several checkboxes, and I want to send back an array of which are checked. I have achieved this by writing the HTML myself, but I'm wondering if there's a way to do it using FormBuilder#check_box.

What I have working

<%= form_with model: @dog, local: true do |my_form| %>
  <label>
    <input type="checkbox"
           name="dog[breeds][]"
           value="labrador">
    Labrador
  </label>
  <label>
    <input type="checkbox"
           name="dog[breeds][]"
           value="husky">
    Husky
  </label>
    <%= my_form.submit 'Save' %>
<% end %>

This works perfectly: the params contain what I expect. If I check the "husky" box and submit, the "breeds" array contains "husky":

"dog"=>{"breeds"=>["husky"]}

But I want to know if there's a way to use my_form.check_box for this, instead of writing out the checkbox HTML myself.

What I've tried for FormBuilder#check_box

<%= form_with model: @dog, local: true do |my_form| %>
  <label>
    <%= my_form.check_box 'breeds[]', value: 'labrador'%>
    Labrador
  </label>
  <label>
    <%= my_form.check_box 'breeds[]', value: 'husky'%>
    Husky
  </label>
  <%= my_form.submit 'Save' %>
<% end %>

This doesn't submit what I expect. In the params, no matter which boxes I check, the "breeds" array is always empty:

"dog"=>{"breeds"=>[]}

Is there a way to do use the FormBuilder helpers for what I'm trying to do?

It really seems like there should be, but I've not been able to find it anywhere.


Solution

  • You should be able to do this like so:

    <%= form_with model: @dog, local: true do |my_form| %>
      <% ['labrador','husky'].each do |breed| %>
          <%= my_form.check_box :breeds, {multiple: true}, breed%>
          <%= my_form.label :breeds, breed.titleize %>
      <%end%>
      <%= my_form.submit 'Save' %>
    <% end %>
    

    The signature for check_box is (object_name, method, options = {}, checked_value = "1", unchecked_value = "0").

    Since you are using the form builder the object_name can be omitted as it will be my_form.

    So we pass:

    ActionView::Helpers::FormHelper#check_box Documentation