Rails:从列中选择唯一值 [英] Rails: select unique values from a column

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

问题描述

我已经有了一个可行的解决方案,但我真的很想知道为什么这不起作用:

I already have a working solution, but I would really like to know why this doesn't work:

ratings = Model.select(:rating).uniq
ratings.each { |r| puts r.rating }

它选择但不打印唯一值,它打印所有值,包括重复值.它在文档中:http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-字段

It selects, but don't print unique values, it prints all values, including the duplicates. And it's in the documentation: http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

推荐答案

Model.select(:rating)

这样做的结果是一个 Model 对象的集合.不是简单的评分.而从 uniq 的角度来看,它们是完全不同的.你可以使用这个:

The result of this is a collection of Model objects. Not plain ratings. And from uniq's point of view, they are completely different. You can use this:

Model.select(:rating).map(&:rating).uniq

或者这个(最有效):

Model.uniq.pluck(:rating)

Rails 5+

Model.distinct.pluck(:rating)

更新

显然,从 rails 5.0.0.1 开始,它只适用于顶级"查询,如上.不适用于集合代理(例如,has_many"关系).

Update

Apparently, as of rails 5.0.0.1, it works only on "top level" queries, like above. Doesn't work on collection proxies ("has_many" relations, for example).

Address.distinct.pluck(:city) # => ['Moscow']
user.addresses.distinct.pluck(:city) # => ['Moscow', 'Moscow', 'Moscow']

在这种情况下,在查询后进行重复数据删除

In this case, deduplicate after the query

user.addresses.pluck(:city).uniq # => ['Moscow']

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

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