Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

ActiveRecord::Calculations#pluck accepts multiple columns

  • Loading branch information...
commit da91b0ae75635b540307c406863620db4073c688 1 parent 35262b7
jeroen authored
View
30 activerecord/lib/active_record/relation/calculations.rb
@@ -166,35 +166,39 @@ def calculate(operation, column_name, options = {})
0
end
- # This method is designed to perform select by a single column as direct SQL query
+ # This method is designed to perform select by a single or multiple columns as direct SQL query
# Returns <tt>Array</tt> with values of the specified column name
# The values has same data type as column.
#
# Examples:
#
# Person.pluck(:id) # SELECT people.id FROM people
+ # Person.pluck([:id, :name]) # SELECT people.id, people.name FROM people
# Person.uniq.pluck(:role) # SELECT DISTINCT role FROM people
# Person.where(:confirmed => true).limit(5).pluck(:id)
#
- def pluck(column_name)
- key = column_name.to_s.split('.', 2).last
+ def pluck(column_names)
+ keys = column_names.is_a?(Array) ? column_names : [column_names.to_s.split('.', 2).last]
- if column_name.is_a?(Symbol) && column_names.include?(column_name.to_s)
- column_name = "#{table_name}.#{column_name}"
+ if column_names.is_a?(Symbol) && self.column_names.include?(column_names.to_s)
+ column_names = "#{table_name}.#{column_names}"
end
- result = klass.connection.select_all(select(column_name).arel, nil, bind_values)
+ result = klass.connection.select_all(select(column_names).arel, nil, bind_values)
types = result.column_types.merge klass.column_types
- column = types[key]
+ column = types[keys[0]]
- result.map do |attributes|
- value = klass.initialize_attributes(attributes)[key]
- if column
- column.type_cast value
- else
- value
+ result = result.map do |attributes|
+ keys.map do |key|
+ value = klass.initialize_attributes(attributes)[key.to_s]
+ if column
+ column.type_cast(value)
+ else
+ value
+ end
end
end
+ column_names.is_a?(Array) ? result : result.flatten
end
private
View
11 activerecord/test/cases/calculations_test.rb
@@ -452,6 +452,17 @@ def test_pluck
assert_equal [1,2,3,4], Topic.order(:id).pluck(:id)
end
+ def test_pluck_multiple_columns
+ assert_equal [
+ [1, "The First Topic"], [2, "The Second Topic of the day"],
+ [3, "The Third Topic of the day"], [4, "The Fourth Topic of the day"]
+ ], Topic.order(:id).pluck([:id, :title])
+ assert_equal [
+ [1, "The First Topic", "David"], [2, "The Second Topic of the day", "Mary"],
+ [3, "The Third Topic of the day", "Carl"], [4, "The Fourth Topic of the day", "Carl"]
+ ], Topic.order(:id).pluck([:id, :title, :author_name])
+ end
+
def test_pluck_type_cast
topic = topics(:first)
relation = Topic.where(:id => topic.id)
Please sign in to comment.
Something went wrong with that request. Please try again.