如何通过has_many评论关系显示收视率最高的专辑 [英] How to display highest rated albums through a has_many reviews relationship

查看:64
本文介绍了如何通过has_many评论关系显示收视率最高的专辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在设置一个简单的ruby/rails应用程序,用户可以在其中查看专辑.在相册的显示页面上,我通过相册控制器

I'm setting up a simple ruby/rails app where users can review albums. On an album's show page I average all the user reviews associated with that album through this code in my albums controller

def show
  @album = Album.find_by_id(params[:id])
  if @album.reviews.present?
    @ratings = Review.where(album_id: @album).average(:rating).truncate(2)
  else
    render 'show'
  end
end

这给了我每张专辑的平均评分.我想在我的首页上(通过其他控制器进行路由)显示平均评分最高的前7张专辑.

This gives me an average rating for each album. On my home page (routed through a different controller) I want to display the top 7 albums with the highest average rating.

我最初所做的就是将此代码放入单独的主页控制器中:

What I originally did was put this code into the separate home page controller:

@albums = Album.all
@ratings = @albums.each {|album| album.reviews.average(:rating).to_f}
@ranked_ratings =  @ratings.sort_by {|rating| rating}
@top_seven = @ranked_ratings.reverse[0...7]

我以为我找到了解决方案,直到我意识到我要显示的是进入数据库的最后7张专辑.

I thought I found the solution until I realized all I'm showing is the last 7 albums entered into the database.

回到绘图板上,我可以使用控制器中的以下代码获取所有相册的数组(数组中的每个元素都是与该相册相关的评论列表):

Going back to the drawing board I have been able to get an array of all the albums (each element within the array is a list of reviews associated with that album) with this code in my controller:

@albums = Album.all
@ratings = @albums.collect {|album| album.reviews}

在这一点上,我一直试图找出如何循环使用@ratings并找到每个album_id的平均评分,然后按最高平均评分对这些记录进行排序并在视图中显示它们的问题.

I'm stuck at this point trying to figure out how to cycle through @ratings and find the average rating for each album_id, then order those records by the highest average rating and display them in a view.

推荐答案

尝试@albums = Album.joins(:reviews).select("album.id, avg(reviews.rating) as average_rating).group("album.id").order("average_rating DESC")

我从以下内容推断出它: Ruby on Rails:根据具有最多评论的平均评分对用户进行排序?

I extrapolated it from: Ruby on Rails: Order users based on average ratings with most reviews?

更新:

改为尝试:@albums = Album.joins(:reviews).select("*, avg(reviews.rating) as average_rating").group("albums.id").order("average_rating DESC")

这篇关于如何通过has_many评论关系显示收视率最高的专辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆