问题
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!
回答1:
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
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>
回答2:
How about some raw SQL?
SELECT AVG(score) FROM movies WHERE category_id = 42
Or in rails:
Movie.where(category_id: 42).average("score")
Read more info here: http://guides.rubyonrails.org/active_record_querying.html#average
回答3:
How about you move SQL
raw query to a database view
:
# movies_view
SELECT m.id, AVG(m.score) avg_score, c.category_id
FROM movies m
JOIN category c
ON m.category_id
So you will need to query from the MovieView
MovieView.find(:movie_id).avg_score
来源:https://stackoverflow.com/questions/15486504/rails-calculate-and-display-average