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']