From 7bf9db529e69cd3cbcedddc0f9af752b0480d13c Mon Sep 17 00:00:00 2001 From: Isaac Sanders Date: Thu, 23 Aug 2012 13:48:02 -0500 Subject: Model.select takes a variable list of arguments. This is a cleaner version of #6916. Closes #3165. --- .../lib/active_record/relation/query_methods.rb | 23 +++++++++++----------- activerecord/test/cases/relations_test.rb | 8 ++++++++ 2 files changed, 20 insertions(+), 11 deletions(-) (limited to 'activerecord') diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 8e6254f918..f6bacf4822 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -136,8 +136,8 @@ module ActiveRecord # Second: Modifies the SELECT statement for the query so that only certain # fields are retrieved: # - # >> Model.select(:field) - # => [#] + # Model.select(:field) + # # => [#] # # Although in the above example it looks as though this method returns an # array, it actually returns a relation object and can have other query @@ -145,25 +145,26 @@ module ActiveRecord # # The argument to the method can also be an array of fields. # - # >> Model.select([:field, :other_field, :and_one_more]) - # => [#] + # Model.select(:field, :other_field, :and_one_more) + # # => [#] # # Accessing attributes of an object that do not have fields retrieved by a select # will throw ActiveModel::MissingAttributeError: # - # >> Model.select(:field).first.other_field - # => ActiveModel::MissingAttributeError: missing attribute: other_field - def select(value = Proc.new) + # Model.select(:field).first.other_field + # # => ActiveModel::MissingAttributeError: missing attribute: other_field + def select(*fields) if block_given? - to_a.select { |*block_args| value.call(*block_args) } + to_a.select { |*block_args| yield(*block_args) } else - spawn.select!(value) + raise ArgumentError, 'Call this with at least one field' if fields.empty? + spawn.select!(*fields) end end # Like #select, but modifies relation in place. - def select!(value) - self.select_values += Array.wrap(value) + def select!(*fields) + self.select_values += fields.flatten self end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 684538940a..b91423351e 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -656,6 +656,14 @@ class RelationTest < ActiveRecord::TestCase assert_raises(ActiveRecord::ActiveRecordError) { Author.limit(10).delete_all } end + def test_select_takes_a_variable_list_of_args + david = developers(:david) + + developer = Developer.where(id: david.id).select(:name, :salary).first + assert_equal david.name, developer.name + assert_equal david.salary, developer.salary + end + def test_select_argument_error assert_raises(ArgumentError) { Developer.select } end -- cgit v1.2.3