我正在尝试在应用程序中显示许多受欢迎的协作,还显示点赞次数(“状态”等于2的协作关联),以及当前用户是否喜欢(基于请求用户在协作关联中的状态)。
我有以下模型:
Collab:
- has_many :collaborations
Collaboration:
- belongs_to :collab
- belongs_to :user
User:
- has_many :collaborations
由于下面的查询,我想要的是:
由10个collab对象组成的数组,其中collab对象包含:
PS:用户一次只能喜欢一个协作,所以每个用户只有一个协作与协作相关。
这就是我现在所拥有的。这给了我十个合作伙伴和协会的数量。我不确定如何仅提供所提供的user_id的协作/协作属性。
popular_collabs = Collab
.left_outer_joins(:collaborations, :reports)
.select("collabs.*, SUM(CASE WHEN collaborations.status = 2 THEN 1 ELSE 0 END) as like_count")
.where(reports: {id: nil})
.where("collabs.deadline >= ?", Date.today)
.group(:id)
.order('like_count DESC')
.limit(10)
答案 0 :(得分:1)
Collab:
- has_many :collaborations
- has_many :users, :through => :collaborations
Collaboration:
- belongs_to :collab
- belongs_to :user
User:
- has_many :collaborations
- has_many :collabs, :through => :collaborations
(如何仅包括由合作伙伴提供的合作/合作属性 提供的user_id。)-
popular_collabs = Collab
.left_outer_joins(:collaborations, :users, :reports)
.select("collabs.*, SUM(CASE WHEN collaborations.status = 2 THEN 1 ELSE 0 END) as like_count")
.where(users: {id: params[:user_id]})
.where(reports: {id: nil})
.where("collabs.deadline >= ?", Date.today)
.group(:id)
.order('like_count DESC')
.limit(10)
或
popular_collabs = Collab
.left_outer_joins(:collaborations, :reports)
.select("collabs.*, SUM(CASE WHEN collaborations.status = 2 THEN 1 ELSE 0 END) as like_count")
.where("collaborations.user_id = ?", params[:user_id])
.where(reports: {id: nil})
.where("collabs.deadline >= ?", Date.today)
.group(:id)
.order('like_count DESC')
.limit(10)