views:

116

answers:

2

I have two scaffold-generated models: Book and Bookbag. A Bookbag has-many Books, and a Book belongs-to a Bookbag. Each Book has a weight, and each Bookbag has an average-weight that is supposed to store the average weight of all of its Books. What is the best way to keep average-weight up to date?

Using a before-save filter on Bookbag doesn't work because it's not called on every update to a Book it contains, and I don't want to update average-weight on every Book update, only when a Book's weight changes.

+3  A: 

A quick solution might be something along these lines:

class Book
  def before_save
    self.bookbag.update_avg if self.weight_changed?
  end
end
mipadi
A: 

There is another solution, if you can afford to recalculate the average as needed.

class Bookbag < ActiveRecord::Base
  has_many :books

  def weight_average
    self.books.average(:weight)
  end
end

You don't need any callbacks in this case, and you leverage your database's ability to do calculations.

François Beausoleil