Distinct values in Rails

First of all don’t do this http://snipplr.com/view/21497/distinct-in-rails. I’m not even linking it since somehow that’s already ranked #5 for “rails distinct” on Google.

One way is to use :select option in ActiveRecord finder.

>> User.all(:select => 'distinct(ip)')
=> [#<User ip: "80.74.172.18">, #<User ip: "80.74.172.13">, ... ]

As you can see this will give you ActiveRecords with only that attribute initialized. Often you need to do something with those distinct values (and not just display them) so it’s more suitable to have values (instead of ActiveRecords) in an array. Use select values for that:

>> User.connection.select_values('select distinct(ip) from users')
=> ["80.74.172.18", "80.74.172.13", ... ]