简体   繁体   English

Rails:选择特定列唯一的所有记录

[英]Rails: Selecting all records that are unique by a specific column

I have a Recommendation model and I would like to select all recommendations that are distinct by their movie_id column. 我有一个推荐模型,我想选择所有由movie_id列区分的推荐。 I've tried a few methods but none that have worked yet: 我尝试了几种方法,但都没有用:

scope :not_duplicate, -> {
    group_by(&:movie_id)
  }

==> doesn't work on a class

scope :not_duplicate, -> {
        uniq_by(&:movie_id)
      }

==> doesn't work on a class

scope :not_duplicate, -> {
        select(:movie_id).group(:movie_id, "recommendations.id")
      }

==> only returns movie_id values and I need entire record

scope :not_duplicate, -> {
        select("recommendations.*").group(:movie_id)
      }

==> PG::GroupingError: ERROR:  column "recommendations.id" must appear in the GROUP BY clause or be used in an aggregate function

I'm sure this is a pretty regular occurrence but for some reason I can't find the solution. 我敢肯定这是很正常的事情,但是由于某种原因我找不到解决方案。 Any ideas? 有任何想法吗?

如果我正确理解了您的问题,可以尝试一下

Recommendation.select {|rec| rec.movie_id == movie_id).uniq

How about: 怎么样:

scope :not_duplicate, -> {
        group(:id, :movie_id).distinct
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM