Either .each do or .all isn't working how I think it should

Posted by user1299656 on Stack Overflow See other posts from Stack Overflow or by user1299656
Published on 2012-03-31T22:50:29Z Indexed on 2012/03/31 23:29 UTC
Read the original article Hit count: 205

So whenever someone rates a shop, I want the Shop model to calculate its new average rating and store that in the database (instead of calculating the average every time someone looks at it). So I wrote the segment of code that follows, and it doesn't work.

The loop always iterates exactly once, no matter how many shop_ratings in the database exist that have the shop's id as their shop_id. I played around with it a bit and found that every time a new rating is submitted the function is called successfully, but it only runs the loop once and sets the average to what the first rating was.

I don't know if the "query" that sets the ratings variable is wrong or if it's the loop that's wrong.

class Shop < ActiveRecord::Base
  has_many :shop_ratings

  attr_accessible :name, :latitude, :longitude

  validates_presence_of :name
  validates_presence_of :latitude
  validates_presence_of :longitude

  def distance_to(lat, long)
    return (self.longitude - long) + (self.latitude - lat)
  end

  def find_average

    total = 0
    count = 0
    ratings = ShopRating.all(:conditions => {:shop_id => id})
    ratings.each do |submission|
      total = total +  submission.rating
      count = count + 1
    end
    update_attribute :average_rating, total/count
  end      

end

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby