3

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!

bork121
  • 113
  • 2
  • 7

3 Answers3

6

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>
Andrea Fiore
  • 1,628
  • 2
  • 14
  • 18
5

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

Ariejan
  • 10,910
  • 6
  • 43
  • 40
0

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