module SimpleFormHelpers::FormBuilderExtensions

Public Instance Methods

collection_check_boxes(attribute_name, model_or_scope, id_attribute_name, display_attribute_name) click to toggle source
# File lib/simple_form_helpers/form_builder_extensions.rb, line 3
def collection_check_boxes(attribute_name, model_or_scope, id_attribute_name, display_attribute_name)
  html_name = "#{self.object_name}[#{attribute_name}][]"

  current_item_ids = self.object.send(attribute_name)

  scope = if model_or_scope.is_a?(Class) && model_or_scope < ActiveRecord::Base
    model_or_scope.all
  else
    model_or_scope
  end

  html1 = '' <<
    @template.hidden_field_tag(html_name) << "\n" <<
    (scope.collect do |item|
      item_id = item.send(id_attribute_name)
      item_display = item.send(display_attribute_name)

      html_id = @template.dom_id(item)
      html2 = '' <<
        '    ' <<
        @template.check_box_tag(
          html_name,
          item_id,
          current_item_ids.include?(item_id),
          id: html_id
        ) << "\n" <<
        '    ' <<
        @template.label_tag(html_id, item_display) <<
        '<br/>' << "\n"
    end).join
  html1.html_safe
end