Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: how can I get unique values from column

How can I get unique values from column in the table? For example, I have this Products table:

ID NAME CATEGORY 1 name1 1st_cat 2 name2 2nd_cat 3 name3 1st_cat 

Here I want to get only 2 values - 1st_cat and 2nd_cat:

<%Products.each do |p|%> <%=p.category%> <%end%> 
like image 994
Oleg Pasko Avatar asked Dec 03 '11 18:12

Oleg Pasko


People also ask

How do I get unique values in a column?

In Excel, there are several ways to filter for unique values—or remove duplicate values: To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates.

How do I get a list of unique values from a table?

The SQL SELECT DISTINCT Statement The SELECT DISTINCT statement is used to return only distinct (different) values. Inside a table, a column often contains many duplicate values; and sometimes you only want to list the different (distinct) values.

Which keyword is use to unique value from column?

The SQL DISTINCT keyword is used in conjunction with the SELECT statement to eliminate all the duplicate records and fetching only unique records.


1 Answers

Two more ways:

Product.select(:category).map(&:category).uniq # Ruby does the work  Product.uniq.pluck(:category) # DB does the work (superior) 

For Rails >= 5.1 use:

Product.distinct.pluck(:category) # DB does the work (superior) 

...because Relation#uniq was deprecated.

like image 150
user664833 Avatar answered Oct 13 '22 06:10

user664833