From 781674de2ffe05ced03daeaaeb670b41c5236f3a Mon Sep 17 00:00:00 2001 From: "Carlos Eduardo L. Lopes" Date: Tue, 8 Jul 2014 16:43:46 -0300 Subject: [PATCH] Accept an array of checked values for #collection_check_boxes Fixes #110 --- CHANGELOG.md | 2 ++ lib/bootstrap_form/form_builder.rb | 8 +++++++- test/bootstrap_form_test.rb | 9 +++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fcd16c437..d5388d9d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ Features: - Added the ability to append/prepend buttons (@retoo) - Added support for time_zone_select + - Accept multiple values, and objects as well, on `collection_check_boxes` + checked option (#114) ## 2.1.1 (2014-04-20) diff --git a/lib/bootstrap_form/form_builder.rb b/lib/bootstrap_form/form_builder.rb index 6eed64281..f30cc41d2 100644 --- a/lib/bootstrap_form/form_builder.rb +++ b/lib/bootstrap_form/form_builder.rb @@ -255,7 +255,13 @@ def inputs_collection(name, collection, value, text, options = {}, &block) collection.each do |obj| input_options = options.merge(label: obj.send(text)) - input_options[:checked] = input_options[:checked] == obj.send(value) if input_options[:checked] + + if checked = input_options[:checked] + input_options[:checked] = checked == obj.send(value) || + checked.try(:include?, obj.send(value)) || + checked == obj || + checked.try(:include?, obj) + end input_options.delete(:class) inputs << block.call(name, obj.send(value), input_options) diff --git a/test/bootstrap_form_test.rb b/test/bootstrap_form_test.rb index f272ea080..529a05f65 100644 --- a/test/bootstrap_form_test.rb +++ b/test/bootstrap_form_test.rb @@ -661,6 +661,15 @@ def setup expected = %{
} assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, :street, checked: 1) + assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, :street, checked: collection.first) + end + + test 'collection_check_boxes renders with multiple checked options correctly' do + collection = [Address.new(id: 1, street: 'Foo'), Address.new(id: 2, street: 'Bar')] + expected = %{
} + + assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, :street, checked: [1, 2]) + assert_equal expected, @builder.collection_check_boxes(:misc, collection, :id, :street, checked: collection) end test 'errors_on hide attribute name in message' do