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'] },