Distinct Values
module ActiveRecord #mixin for active record module ModelHelper # module name def self.included(base) # include this into the base of the class instance base.class_eval do # evaluate the below (class << self;self;end).class_eval do def self.distinct_values(column) find(:all, :select => "DISTINCT #{column}").map{|x| x.send(column)} if column_names.include?(column) end end </a> end end end end
I like to setup a file in the /lib directory to hold model_helper.rb. I tend to put functions that I like to mix into all of my models into this file. This keeps things dry and it prevents me from running all over wondering where a certain active record model function is located.
def self.distinct_values(column) find(:all, :select => "DISTINCT #{column}").map{|x| x.send(column)} if column_names.include?(column) end
After I mix this function in to all the active records objects I’m give the ability to call it like this:
distinct_items = Model.distinct_values("column_name") #> ["value1","value2","value3"]
This will return distinct values of a model, instead of the objects themselves. I find this useful in projects where there is sometimes an intentional lack of normalization on a table.
table: posts +-----+----------+ | id | category | +-----+----------+ | 5 | ruby | | 35 | ruby | | 52 | news | | 53 | news | | 63 | news |
so now we can just call.
Post.distinct_values("category") #-> ["ruby","news"]
This is useful for filling dropdown lists, select boxes, etc.