在我的 Rails 应用程序中,我有这个:
class Invoice < ActiveRecord::Base
  has_many :payments
  before_save :save_outstanding_amount
  def save_outstanding_amount # atomic saving
    self.outstanding_amount = new_outstanding_amount
  end
  def update_outstanding_amount # adds another SQL query
    update_column(:outstanding_amount, new_outstanding_amount)
  end
  private
    def new_outstanding_amount    
      total - payments.sum(&:amount)
    end
end
如何使这种动态化,以便从类的所有实例调用第一个方法,Invoice从其他类的所有实例(例如Payment该类)调用第二个方法?