From 24dd492386a99cd630536423b942dace53b1f925 Mon Sep 17 00:00:00 2001 From: Ben Moss & Micah Young Date: Mon, 18 Mar 2013 10:08:04 -0400 Subject: [PATCH] Fix the way `detect_common_display_methods` finds label & value methods It was previously looking at an instance of the `collection` instead of the `collection_classes`. Since the grouped collection input supplies a list of collection classes that differ from the regular collection, it was incorrectly looking for labelling and value methods on the option instances, rather than the optgroup instances. --- lib/simple_form/inputs/collection_input.rb | 7 ++++--- .../grouped_collection_select_input_test.rb | 18 ++++++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/simple_form/inputs/collection_input.rb b/lib/simple_form/inputs/collection_input.rb index 020b7e13..e21c9baf 100644 --- a/lib/simple_form/inputs/collection_input.rb +++ b/lib/simple_form/inputs/collection_input.rb @@ -63,6 +63,7 @@ module SimpleForm end def detect_common_display_methods(collection_classes = detect_collection_classes) + return {} if collection_classes == [] collection_translated = translate_collection if collection_classes == [Symbol] if collection_translated || collection_classes.include?(Array) @@ -70,10 +71,10 @@ module SimpleForm elsif collection_includes_basic_objects?(collection_classes) { label: :to_s, value: :to_s } else - sample = collection.first || collection.last + sample = collection_classes.first - { label: SimpleForm.collection_label_methods.find { |m| sample.respond_to?(m) }, - value: SimpleForm.collection_value_methods.find { |m| sample.respond_to?(m) } } + { label: SimpleForm.collection_label_methods.find { |m| sample.instance_methods.include?(m) }, + value: SimpleForm.collection_value_methods.find { |m| sample.instance_methods.include?(m) } } end end diff --git a/test/inputs/grouped_collection_select_input_test.rb b/test/inputs/grouped_collection_select_input_test.rb index 5e235639..80507d1b 100644 --- a/test/inputs/grouped_collection_select_input_test.rb +++ b/test/inputs/grouped_collection_select_input_test.rb @@ -79,6 +79,24 @@ class GroupedCollectionSelectInputTest < ActionView::TestCase end end + test 'grouped collection finds default label methods on the group objects' do + option_list = ['Jose', 'Carlos'] + + GroupedClass = Struct.new(:to_label, :options) + group = GroupedClass.new("Authors", option_list) + + with_input_for @user, :tag_ids, :grouped_select, + collection: [group], + group_method: :options + + assert_select 'select.grouped_select#user_tag_ids' do + assert_select 'optgroup[label=Authors]' do + assert_select 'option', 'Jose' + assert_select 'option', 'Carlos' + end + end + end + test 'grouped collection accepts label and value methods options' do with_input_for @user, :tag_ids, :grouped_select, collection: { 'Authors' => ['Jose', 'Carlos'] },