Unique Values – Ruby on Rails

Just a quick post on how to select unique values in rails using the uniq operator:

1
2
3
4
5
6
7
8
9
10
11
#All recent categories
<% recent_categories = Category.joins(:products).where('products.user_id = ?', current_user.id).order('products.created_at desc') %>
 
#Results
Cars
Trucks
Cars
Technology
Phones
Technology
...
1
2
3
4
5
6
7
8
#Unique recent categories
<% recent_categories = Category.joins(:products).where('products.user_id = ?', current_user.id).order('products.created_at desc').uniq %>
 
Cars
Trucks
Technology
Phones
...

Leave a Reply