ActiveRecord and SELECT DISTINCT

Blue Cup 1 (photo by woodsy)I'm writing this post for two reasons:

  1. For some reason, I couldn't find a lot of information on ActiveRecord and SELECT DISTINCT().
  2. 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.

My Bookshelf

Reading Now

Other Stuff