Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Model.select takes a variable list of arguments.

This is a cleaner version of #6916.

Closes #3165.
  • Loading branch information...
commit 7bf9db529e69cd3cbcedddc0f9af752b0480d13c 1 parent 764deab
@isaacsanders isaacsanders authored Francesco Rodriguez committed
View
23 activerecord/lib/active_record/relation/query_methods.rb
@@ -136,8 +136,8 @@ def references!(*args)
# Second: Modifies the SELECT statement for the query so that only certain
# fields are retrieved:
#
- # >> Model.select(:field)
- # => [#<Model field:value>]
+ # Model.select(:field)
+ # # => [#<Model field:value>]
#
# 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 @@ def references!(*args)
#
# The argument to the method can also be an array of fields.
#
- # >> Model.select([:field, :other_field, :and_one_more])
- # => [#<Model field: "value", other_field: "value", and_one_more: "value">]
+ # Model.select(:field, :other_field, :and_one_more)
+ # # => [#<Model field: "value", other_field: "value", and_one_more: "value">]
#
# Accessing attributes of an object that do not have fields retrieved by a select
# will throw <tt>ActiveModel::MissingAttributeError</tt>:
#
- # >> 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
View
8 activerecord/test/cases/relations_test.rb
@@ -656,6 +656,14 @@ def test_delete_all_limit_error
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
Please sign in to comment.
Something went wrong with that request. Please try again.