Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 query unique by single attribute

So this is more of an arel question than anything but here's what I am trying to do.

I have three objects lets say, called Items

<Item id: 1, name: 'Book'>
<Item id: 2, name: 'Car'>
<Item id: 3, name: 'Book'>

I want to do a query that will just return only one of each unique "name" attributes.

Something like Item.select('distinct(name), items.*')

This doesn't work though, it still returns all three items.

How can I form this query so that it only returns:

<Item id: 1, name: 'Book'>
<Item id: 2, name: 'Car'>
like image 636
goddamnyouryan Avatar asked Aug 05 '13 03:08

goddamnyouryan


3 Answers

If you want to get the entire model back, but still maintain uniqueness, you can use this:

Item.select('distinct on (name) *')

I've only tested this with a Postgres database. It may or may not work with mysql.

like image 153
BananaNeil Avatar answered Oct 26 '22 03:10

BananaNeil


Please try this:

Item.select('distinct name')
like image 11
vee Avatar answered Oct 26 '22 04:10

vee


If you only need an array with the names, without the ID, you can do:

Item.pluck(:name).uniq

SQL query result:

#=> SELECT `items`.`name` FROM `items`

** edit **

The uniq is ran on the array of records. Be careful if you expect a lot of records. SQL Distinct is much faster.

If so, use vee's answer above, with a map:

Item.select('distinct name').map(:name)

like image 4
Frexuz Avatar answered Oct 26 '22 03:10

Frexuz