ActiveRecord and SELECT DISTINCT
I’m writing this post for two reasons:
- For some reason, I couldn’t find a lot of information on ActiveRecord and
SELECT DISTINCT(). - I’m hoping some Ruby / ActiveRecord guru will stumble across this and provide a better solution.
Recently, I was working on a project written in Ruby with ActiveRecord that required me to draw a list of host names from a database and perform some actions on them. The actions aren’t really important here. What I had a hard time finding was the ActiveRecord way of performing a SELECT DISTINCT() SQL query. My search came up empty, so I was forced to use the find_by_sql() method below. Obviously, I’ve changed the code to make it generic and not violate any non-disclosure agreements I might have.
records = Class.find_by_sql(["SELECT DISTINCT(hostname) FROM table"])
This code works just fine, but it lacks a certain elegance. One thing that really bothers me is that I have to hardcode the table name into this line of code. If we make a change to the table name some time down the road, this line will have to be found and modified. Blech.
Get Slaptijack updates for free.

Get Slaptijack updates delivered to your Inbox or RSS Reader for free!
November 20th, 2007 at 6:43 pm
Dude,
You can get away with something like this:
records = Class.find(:all, :select => “DISTINCT(hostname)”)
It’s a bit cleaner.
November 21st, 2007 at 1:49 am
Thanks for the heads up, Mando. I’ll give that a go.
January 31st, 2008 at 4:38 pm
Check out this page! I has a lot of good examples on how to do the subtle SQL stuff (like DISTINCT).
http://railsmanual.com/module/ActiveRecord::Calculations::ClassMethods
January 31st, 2008 at 4:43 pm
@Greg:
Thanks for the link. That’s a great resource.