Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Last active Aug 20, 2020
Embed
What would you like to do?
Adderall
# app/lib/adderall.rb
module Adderall
def adderall(column_name, relation = self, filter = :itself)
owner = proxy_association.owner
records = proxy_association.target
if loaded? || owner.new_record?
relation = none
else
records = records.select(&:new_record?)
end
relation.sum(column_name) + records.select(&filter).sum(&column_name)
end
end
# Example usage:
# app/models/record/invoice.rb
class Record::Invoice < ApplicationRecord
before_validation do
self.sub_total = receivables.computed_line_price_sum
end
has_many :receivables, autosave: true do
include Adderall
def computed_line_price_sum
adderall(:line_price, not_freight, :not_freight?)
end
end
#...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment