Unique Values – Ruby on Rails

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

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.