'Can I make a modification to a child force a validation on a parent when using Active Record Autosave Association?
I am looking for how to trigger a validation on a parent when a child is modified or deleted.
Some background in case I am asking the wrong question: I am trying to implement some basic double entry accounting in a Rails app. I have found a couple accounting Gems but they seem poorly maintained and overly complex. I also want to have complete control so I am building it myself.
My abstraction currently is a parent class, Txn (avoiding Transaction becuase although it is not a reserved word, it doesn't play well with Active Record). Txn has meta data about the transaction, as well as many LineItems.
LineItems are pretty simple; they have a debit_amount, credit_amount, account_id, and txn_id. I am trying to enforce a constraint on all LineItems belonging to a single Txn such that the sum of debits == the sum of credits. Autosave Association gets me most of the way there, allowing me to put a validator in Txn, but I want to ensure, at the ORM level, that if a LineItem is updated or deleted, that the parent Txn will re-validate and only allow the LineItem to be updated or deleted if all remaining LineItems balance.
I am hesistant to start messing with callbacks on the LineItem triggering a change to the Txn for fear of creating cirular logic resulting in a race condition.
I welcome any suggestions or resources as well as specific steps and or callbacks I should use.
class Txn
has_many :lineItems, autosave: true
end
class LineItem
belongs_to :txn
end
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|