简体   繁体   English

Rails:has_many:through。 需要返回具有唯一列值的记录

[英]Rails: has_many :through. Need to return records that have unique column value

In my User model: 在我的用户模型中:

has_many :followed_recommendations, :through => :followed_users, :source => :recommendations, class_name: Recommendation

A recommendation has a movie_id column. 推荐中有movie_id列。 A user can get multiple recommendations for the same movie but I would like to return only 1. 用户可以为同一部电影获得多个推荐,但我只想返回1。

So I need a way to get only the :followed_recommendations that have a unique movie_id value but not sure how to do this. 因此,我需要一种方法来仅获取具有唯一movie_id值的:followed_recommendations,但不确定如何执行此操作。 The example I keep seeing coming up is: 我不断看到的例子是:

has_many :products, -> { distinct }, through: :orders

But that is looking at the full product record whereas I just want distinct by one column. 但这只是查看完整的产品记录,而我只想按一栏区分。

你试过了吗:

 has_many :followed_recommendations, ->{group(:movie_id)}, :through => :followed_users, :source => :recommendations, class_name: Recommendation

You have a movie_id column in your Recommendation model, so I assume you have this association. 在“ Recommendation模型中有一个movie_id列,因此我假设您具有这种关联。

class Recommendation < ActiveRecord::Base
  belongs_to :movie
end

Then you could use the way with distinct like you posted in your question. 然后,您可以使用与问题中所张贴的distinct的方式。

class User < ActiveRecord::Base
  has_many :followed_recommendations, :through => :followed_users, :source => :recommendations, class_name: Recommendation
  has_many :followed_recommended_movies, -> { distinct }, :through => :followed_recommendations, :class_name => Movie, source: :movie
end

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

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