Skip to content

Instantly share code, notes, and snippets.

@dbalatero
Created July 11, 2013 20:07
Show Gist options
  • Select an option

  • Save dbalatero/5978762 to your computer and use it in GitHub Desktop.

Select an option

Save dbalatero/5978762 to your computer and use it in GitHub Desktop.
class Order < ActiveRecord::Base
has_many :line_items
before_validation :initialize_subtotal # good
before_save :recalculate_subtotal # bad
private
def recalculate_subtotal
self.subtotal = self.line_items.map(&:subtotal).sum
end
def initialize_subtotal
self.subtotal ||= 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment