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

时间:2016-06-29 23:33:09

标签: ruby-on-rails activerecord

在我的用户模型中:

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

推荐有一个movie_id列。用户可以获得同一部电影的多个推荐,但我只想返回1.

所以我需要一种方法来只获得:followed_recommendations具有唯一的movie_id值,但不知道如何做到这一点。我不断看到的例子是:

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

但是,这是在查看完整的产品记录,而我只想要一列不同。

2 个答案:

答案 0 :(得分:0)

你有没有尝试过:

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

答案 1 :(得分:0)

您的movie_id模型中有Recommendation列,因此我假设您有此关联。

class Recommendation < ActiveRecord::Base
  belongs_to :movie
end

然后你就可以使用你在问题中发布的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