'Manual collection check boxes in Simple Form

I'm building a form using Simple Form where I must manually loop over a collection of records which are candidates for a HABTM relationship. I must do a manual loop because I need to render additional information about the records in a table, so I can't use Simple Form's collection_check_boxes.

Models:

class Foo < ActiveRecord::Base
  has_and_belongs_to_many :bars
end

class Bar < ActiveRecord::Base
  has_and_belongs_to_many :foos
end

View so far (HAML):

= f.simple_for_form @foo do |f|
  %table
    - @bars.each do |bar|
      %tr
        %td
          # Line of interest:
          = f.input :bar_ids, as: :boolean, label: bar.name
        %td
          = bar.additional_information

How do I tell Simple Form that f.input :bar_ids is part of an array so that it will name the field foo[bar_ids][] and assign a value of bar.id?



Solution 1:[1]

Turns out it's reasonably straightforward, thanks to this post from 2012.

= f.simple_for_form @foo do |f|
  %table
    = f.collection_check_boxes :bars, @bars, :id, :name do |builder|
      %tr
        %td
          = builder.check_box
          = builder.label 
        %td
          = builder.object.additional_information

Solution 2:[2]

You can test

f.input :bar_ids, as: :boolean, label: bar.name, as: :checkboxes

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tristanm
Solution 2 Vline