Skip to content

Instantly share code, notes, and snippets.

@skojin
Created February 15, 2011 16:16
Show Gist options
  • Save skojin/827728 to your computer and use it in GitHub Desktop.
Save skojin/827728 to your computer and use it in GitHub Desktop.
extend rails3 activerecord public interface with powerfull connection.select_value(s) method, put this file to config/initializers/
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
@skojin
Copy link
Author

skojin commented Feb 15, 2011

primary need for Model.select_id, in my test it two time faster then Model.select('id').map{|t| t.id}

@kball
Copy link

kball commented Jun 21, 2011

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

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