sharataka
sharataka

Reputation: 5132

How to calculate average in rails app view through has_many?

I am trying to calculate the average rating in the view of my rails app through a has_many relationship.

Models:

class Review < ActiveRecord::Base
  belongs_to :product
  attr_accessible :rating, :review
  belongs_to :user
end


class Product < ActiveRecord::Base
  attr_accessible  :name
  has_many :reviews
  has_many :supplements
  acts_as_taggable
end

Controller:

@products = Product.all

View:

<% @products.each do |product| %>
    <%= product.NOT SURE %>
<% end %>

I would like this to show the average rating for that given product in the view, but am not sure how. Any advice?

Upvotes: 2

Views: 1834

Answers (1)

lurker
lurker

Reputation: 58224

In your view, you want something like:

<% @products.each do |product| %>
    <%= product.average_rating %>
<% end %>

Now you just need to do the average_rating, and that can go in the model:

def average_rating
    if self.reviews.size > 0
        self.reviews.average(:rating)
    else
        'undefined'
    end
end

So average_rating sums up the review ratings and divides by the number of ratings for the average. You can polish it up for format, etc.

Upvotes: 4

Related Questions