Skip to content

Instantly share code, notes, and snippets.

@pdbradley
Created June 6, 2018 03:02
Show Gist options
  • Save pdbradley/2367230eb00831641cdf50ab994350f8 to your computer and use it in GitHub Desktop.
Save pdbradley/2367230eb00831641cdf50ab994350f8 to your computer and use it in GitHub Desktop.
trigger to update invoice total whenever there is an adjustment change
class AddTriggerForInvoiceAmount < ActiveRecord::Migration[5.1]
def change
reversible do |dir|
dir.up do
execute <<-SQL
CREATE OR REPLACE FUNCTION calculate_invoice_current_balance()
RETURNS trigger AS $calc_invoice_balance$
BEGIN
IF (TG_OP = 'DELETE') THEN
UPDATE invoices
SET triggered_invoice_amount = (SELECT SUM(invoice_amount)
FROM invoice_adjustments
WHERE invoice_id = OLD.invoice_id)
WHERE id = OLD.invoice_id;
RETURN OLD;
ELSE /* below is for insert or update */
UPDATE invoices
SET triggered_invoice_amount = (SELECT SUM(invoice_amount)
FROM invoice_adjustments
WHERE invoice_id = NEW.invoice_id)
WHERE id = NEW.invoice_id;
RETURN NEW;
END IF;
END;
$calc_invoice_balance$ LANGUAGE plpgsql;
CREATE TRIGGER invoice_adjustments_added
AFTER UPDATE OR INSERT OR DELETE
ON invoice_adjustments
FOR EACH ROW
EXECUTE PROCEDURE calculate_invoice_current_balance();
SQL
end
dir.down do
execute <<-SQL
DROP TRIGGER IF EXISTS invoice_adjustments_added ON invoice_adjustments;
DROP FUNCTION IF EXISTS calculate_invoice_current_balance();
SQL
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment