diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index e9ed5d99793e9..52531a3520a8c 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -66,11 +66,11 @@ def reset @target = [] end - def select(select = nil) + def select(*fields) if block_given? load_target.select.each { |e| yield e } else - scope.select(select) + scope.select(*fields) end end diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb index 0dabe256e32c9..a28cc2993b6aa 100644 --- a/activerecord/lib/active_record/associations/collection_proxy.rb +++ b/activerecord/lib/active_record/associations/collection_proxy.rb @@ -75,7 +75,7 @@ def loaded? # # # # # ] # - # person.pets.select([:id, :name]) + # person.pets.select(:id, :name ) # # => [ # # #, # # #, @@ -106,8 +106,8 @@ def loaded? # # #, # # # # # ] - def select(select = nil, &block) - @association.select(select, &block) + def select(*fields, &block) + @association.select(*fields, &block) end # Finds an object in the collection responding to the +id+. Uses the same diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index c6291e8aa4200..e45efb01617c2 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -455,7 +455,11 @@ def test_default_select end def test_select_query_method - assert_equal ['id'], posts(:welcome).comments.select(:id).first.attributes.keys + assert_equal ['id', 'body'], posts(:welcome).comments.select(:id, :body).first.attributes.keys + end + + def test_select_with_block + assert_equal [1], posts(:welcome).comments.select { |c| c.id == 1 }.map(&:id) end def test_select_without_foreign_key