Last active
August 20, 2020 12:56
-
-
Save inopinatus/2aa1bde5d6cddeec6e0d1421923e6e35 to your computer and use it in GitHub Desktop.
Adderall
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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