Created
February 15, 2011 16:16
-
-
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/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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