-
-
Save skojin/827728 to your computer and use it in GitHub Desktop.
module ActiveRecordSelectAttributesExtension | |
def select_id(field = 'id') | |
select_values(field) | |
end | |
def select_values(field = nil) | |
scope = field ? self.scoped.select(field) : self.scoped | |
connection.select_values(scope.to_sql) | |
end | |
def select_attributes(fields = nil) | |
scope = fields ? self.scoped.select(fields) : self.scoped | |
connection.send(:select_all, scope.to_sql) | |
end | |
end | |
::ActiveRecord::Base.class_eval do | |
extend ActiveRecordSelectAttributesExtension | |
end |
Fascinatingly, in Rails 3.0.7, select_values fails for anything that has been scoped using 'where'. However, select_id continues to work, despite the fact that it just calls select_values.
This is because the class ActiveRecord::Relation actually defines select_values as a simple accessor with no arguments, so if you do something
User.where(:active => true).select_values(:id)
It fails with an ArgumentError: wrong number of arguments (1 for 0)
But if you call
User.where(:active => true).select_id
it proxies over to the User model, which then has select_values defined appropriately.
As written, you could actually use select_id for any field, but I think it is probably better to rename select_values to something like select_columns or something similar
primary need for Model.select_id, in my test it two time faster then Model.select('id').map{|t| t.id}