2016-06-29 81 views
0

在我的用戶模型中記錄:Rails:has_many:通過。需要返回具有獨特的列值

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 

但是,這是看完整的產品記錄,而我只是想區分一列。

回答

0

你嘗試:

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

我得到PG :: GroupingError:錯誤:列「recommendations.id」必須出現在GROUP BY子句中或用於聚合函數中 –

0

您的Recommendation模型movie_id列,所以我想你有這樣的相關性。

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