Skip to content

Commit

Permalink
Use the first non-empty object to detect the label and value method for
Browse files Browse the repository at this point in the history
grouped select

Fixes #978
  • Loading branch information
rafaelfranca committed Apr 2, 2014
1 parent 44e807f commit 7ed2822
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
### bug fix
* Collection input that uses automatic collection translation properly sets checked values.
Closes [#971](https://github.com/plataformatec/simple_form/issues/971) [@nashby](https://github.com/nashby)
* Grouped collection use the first non-empty object to detect label and value methods.
* Collection input generates `required` attribute if it has `prompt` option. [@nashby](https://github.com/nashby)

## deprecation
Expand Down
2 changes: 1 addition & 1 deletion lib/simple_form/inputs/grouped_collection_select_input.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def grouped_collection

# Sample collection
def collection
@collection ||= grouped_collection.first.try(:send, group_method) || []
@collection ||= grouped_collection.map { |collection| collection.try(:send, group_method) }.detect(&:present?) || []
end

def group_method
Expand Down
18 changes: 18 additions & 0 deletions test/inputs/grouped_collection_select_input_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,24 @@ class GroupedCollectionSelectInputTest < ActionView::TestCase
end
end

test 'grouped collections finds the default label method from the first non-empty object' do
Agent = Struct.new(:id, :name)
agents = [["First", []], ["Second", [Agent.new(7, 'Bond'), Agent.new(47, 'Hitman')]]]

with_input_for @user, :tag_ids, :grouped_select,
collection: agents,
group_label_method: :first,
group_method: :last,
include_blank: false

assert_select 'select.grouped_select#user_tag_ids' do
assert_select 'optgroup[label=Second]' do
assert_select 'option[value=7]', 'Bond'
assert_select 'option[value=47]', 'Hitman'
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'] },
Expand Down

0 comments on commit 7ed2822

Please sign in to comment.