Skip to content

Instantly share code, notes, and snippets.

@jcf
Created February 9, 2012 17:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jcf/1781411 to your computer and use it in GitHub Desktop.
Save jcf/1781411 to your computer and use it in GitHub Desktop.
Backport pluck to Rails 3.1
# config/initializers/extensions/active_record.rb
module ActiveRecord
class Base
class << self
delegate :pluck, to: :scoped
end
end
class CollectionProxy
delegate :pluck, 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)
#
def pluck(column_name)
scope = self.select(column_name)
self.connection.select_values(scope.to_sql).map! do |value|
type_cast_using_column(value, column_for(column_name))
end
end
end
end
@divoxx
Copy link

divoxx commented Aug 24, 2012

That's awesome. There is only one detail, the self.select you're using, if its on a CollectionProxy, it will select

.* on tables involved on joins. That is why my example was using Arel::SelectManager#projections=

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment