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

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

问题描述

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

 收视率= Model.select(:评级).uniq
ratings.each {| R |把r.rating}
 

它可以选择,但是不打印唯一值,它打印的所有值,包括重复。而且它在文档中:<一href="http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields">http://guides.rubyonrails.org/active_record_querying.html#selecting-specific-fields

解决方案

  Model.select(:评分)
 

这个结果是型号对象的数组。不是普通的收视率。而从 uniq的的角度来看,他们是完全不同。您可以使用此:

  Model.select(:等级).MAP(安培;:评级).uniq
 

或此(最有效的)

  Model.uniq.pluck(:评分)
 

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 }

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)

Result of this is an array 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

or this (most efficient)

Model.uniq.pluck(:rating)

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

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