Skip to content

Instantly share code, notes, and snippets.

@gstark
Created July 20, 2014 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gstark/5db29683e59ad96a6a70 to your computer and use it in GitHub Desktop.
Save gstark/5db29683e59ad96a6a70 to your computer and use it in GitHub Desktop.
pluck backported to Rails 3.x
module ActiveRecord
class Base
class << self
delegate :pluck, :ids, :to => :scoped
end
end
class CollectionProxy
delegate :pluck, :ids, :to => :scoped
end
# = Active Record Relation
class Relation
# 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.uniq.pluck(:role) # SELECT DISTINCT role FROM people
# Person.where(:confirmed => true).limit(5).pluck(:id)
#
# Person.pluck(:id, :name)
# # SELECT people.id, people.name FROM people
# # [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']]
#
def pluck(*column_names)
# Make sure we have an array of text representations of the column names
column_names = Array(column_names).map(&:to_s)
# Define a scope for selecting just those fields
scope = self.select(column_names.join(", "))
# Precache the column definitions of those fields
column_definitions = Hash[column_names.map { |column| [column, column_for(column)] }]
# Select the resultant SQL
select_all = self.connection.select_all(scope.to_sql)
# Map the row hashes returned from select_all into arrays such that the
# values are in the same order as the originally supplied columns
results = select_all.map! do |row_hash|
column_names.map.with_index do |column, index|
value = row_hash.values[index]
column_def = column_definitions[column_names[index]]
type_cast_using_column(value, column_def)
end
end
# If only a single column was given then flatten the results
column_names.size == 1 ? results.flatten : results
end
def ids
pluck("#{table_name}.id")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment