Search code examples
ruby-on-railsrubysimple-form

Simple Form - Multiple attributes in checkbox group


I have a User Model with the following attributes:

#  full_time                :boolean
#  part_time                :boolean
#  contract                 :boolean

I would like to create a simple form checkboxes group for these attributes. From what I've been able to understand, the simple form api is meant to map to has_many & has_and_belongs_to_many associations, as follows:

f.collection_check_boxes :role_ids, Role.all, :id, :name

Is there a way to handle updating multiple attributes on the given model within the form's API guidelines? Or is this an indication that should I be modeling the data in a different way?


Solution

  • f.collection_check_boxes is a generic method for generating multiple checkboxes with arbitrary name/value, for a single attribute. The sample you gave is mentioned in the docs as a last one for this method, probably because f.association is way better for association attributes.

    <%= f.association :role, Role.all %>
    

    In case of your attributes, I don't think f.collection_check_boxes is applicable. If the attributes aren't mutually exclusive, then I don't see anything wrong - stick with them and just give each one a checkbox of it's own.

    <%= f.input :full_time %>
    <%= f.input :part_time %>
    <%= f.input :contract %>
    

    simple_form will detect their type and generate a checkbox for each. Use wrapper: false option, if you want to get rid of wrapper divs and group them more tightly.

    If they were mutually exlusive, then an integer column and enum would be probably a better idea.