Rails计算并显示平均值 [英] Rails calculate and display average
问题描述
我正在尝试对特定类别的平均得分.我有一张表格,其中包含导演,电影,类型,评分和得分的列表.当用户点击电影时,我希望他们能够看到该类型所有其他电影的平均得分.
I'm trying to average scores within a particularly category. I have a table that contains a list of directors, movies, genres, ratings and scores. When the user clicks on a movie I'd like them to be able to see the average score for all other movies in that genre.
我认为我必须将均值方法与条件结合使用.就是说,我无法在线找到有关此特定主题的任何有用文档.如果有人可以将我指向指导或文章的方向,该指导或文章解释了如何根据条件计算平均值并在视图中显示平均值,我将不胜感激!
I think that I have to use the average method in conjunction with a condition. That said I haven't been able to find any useful documentation online regarding this specific topic. If someone could point me in the direction of a guide or article that explains how to calculate averages with conditions and display them in a view, I would greatly appreciate it!
推荐答案
Together with other calculations, ActiveRecord provides a method called average. You can use it by implementing something like this:
class Movie
def self.average_by_genre(genre)
average(:rating).where(:genre => genre)
end
end
或者,您也可以将其实现为Movie模型的实例方法.
Alternatively, you can also implement it as an instance method of the Movie model.
class Movie
def average_rating
self.class.average(:rating).where(:genre => self.genre)
end
end
这将使您可以直接从视图中调用该方法.
This would let you call the method directly from your view.
<article>
<header>
<h1><%= @movie.title %></h1>
</header>
<p>
<span>Average rating for genre <%= @movie.genre %>:</span>
<%= @movie.average_rating %>
</p>
</article>
这篇关于Rails计算并显示平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!