Unique Values – Ruby on Rails

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

#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
...
#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