Plugins - Values Of
Add to favoritesAdds a values_of class method to ActiveRecord::Base classes.
Under the hood is simply does a construct_finder_sql, forcing :select to be whatever you pass in the first argument, using that to call connection.select_values and (optionally) type_cast()ing the resulting values.
Aside from being prettier than passing a honking long SQL string to connection.select_values, the use of construct_finder_sql also ensures that any with_scope() in effect will be honored.
USAGE:
values_of(colspec, options = {}, &block)
- colspec can be a:
Symbol - in which case you are selecting that column and (unless you pass a block) you want the in-built rails type-casting to turn the raw text sql result into the relevant type.
String - an sql expression you want to use for the :select portion of your query. Note that if you pass a String then values_of won’t try to automatically type_cast your returned values. See the info about &block below.
- options are anything normally accepted by ActiveRecord::Base#find.
- &block is an optional block that will be collect()ed on your returned string
values.
Note that &block overrides any implicit type_cast()ing that would be done if you pass a Symbol as a colspec.
EXAMPLES:
Project.values_of(:created_on, :limit => 10) # SELECT projects.`created_on` FROM projects LIMIT 10 # [Date, Date, Date, … ]
Project.values_of(‘created_on’, :limit => 10) # SELECT created_on FROM projects LIMIT 10 # ["2006-01-24", "2006-02-21", .…]
Project.values_of("distinct DATE_FORMAT(created_on,’%Y-%m-1’)", :limit => 10) # SELECT distinct DATE_FORMAT(created_on,’%Y-%m-1’) FROM projects LIMIT 10 # ["2006-01-1", "2006-02-1", "2006-03-1", .…]
Project.values_of("distinct DATE_FORMAT(created_on,’%Y-%m-1’)", :limit => 10) do |raw_val|
raw_val.to_date
end # SELECT distinct DATE_FORMAT(created_on,’%Y-%m-1’) FROM projects LIMIT 10 # [Date, Date, Date, … ]
User.find(1).projects.values_of(:id) # SELECT projects.`id` FROM projects WHERE (projects.user_id = 1) [1, 8, 16, …]
