Last active
December 9, 2022 18:55
-
-
Save lelandsmith/9438766 to your computer and use it in GitHub Desktop.
Multiple checkboxes for ruby array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
NOTE: If you use
nil
as the unchecked value, it will not automatically include ahidden_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 ofnil
, it will generate thehidden_field_tag
automatically and you should be in good shape. Then, you may want to use abefore_save
to callcompact_blank!
to remove any empty Strings in the serialized Array.