Skip to content

Instantly share code, notes, and snippets.

@lelandsmith
Last active December 9, 2022 18:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lelandsmith/9438766 to your computer and use it in GitHub Desktop.
Save lelandsmith/9438766 to your computer and use it in GitHub Desktop.
Multiple checkboxes for ruby array
#MODEL
serialize :storage_type
#CONTROLLER
:storage_type => []
#FORM
#STORE = model
<div class="field">
<%= check_box("store", :storage_type, {:multiple => true}, "Self Storage", nil) %> Self Storage
<%= check_box("store", :storage_type, {:multiple => true}, "fetch", nil) %> fetch
<%= check_box("store", :storage_type, {:multiple => true}, "roll_over", nil) %> roll_over
</div>
#OUTPUTTED
<div class="field">
<input checked="checked" id="store_storage_type_self_storage" name="store[storage_type][]" type="checkbox" value="Self Storage"> Self Storage
<input checked="checked" id="store_storage_type_fetch" name="store[storage_type][]" type="checkbox" value="fetch"> fetch
<input checked="checked" id="store_storage_type_roll_over" name="store[storage_type][]" type="checkbox" value="roll_over"> roll_over
</div>
@joshuapinter
Copy link

NOTE: If you use nil as the unchecked value, it will not automatically include a hidden_field_tag which the unset value. This means that if you uncheck all of the boxes (after at least one of them is already set), it will not submit anything and the previous values will remain.

By using any empty String ("") instead of nil, it will generate the hidden_field_tag automatically and you should be in good shape. Then, you may want to use a before_save to call compact_blank! to remove any empty Strings in the serialized Array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment