Rails:如何从列中获取唯一值 [英] Rails: how can I get unique values from column

查看:56
本文介绍了Rails:如何从列中获取唯一值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从表中的列中获取唯一值?例如,我有这个 Products 表:

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

这里我只想得到 2 个值 - 1st_cat 和 2nd_cat:

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

<%Products.each do |p|%>
<%=p.category%>
<%end%>

推荐答案

另外两种方式:

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

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

对于 Rails >= 5.1 使用:

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

...因为 Relation#uniq 已被弃用.

这篇关于Rails:如何从列中获取唯一值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆