Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>One way to achieve what you want will be to use <a href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html" rel="nofollow">ActiveRecord::Callbacks</a>:</p> <pre><code>class Payment &lt; ActiveRecord::Base attr_accessible :amount, :method, :payment_date, :reference_no, :invoice_id belongs_to :invoice after_create :update_invoice_balance def update_invoice_balance current_balance = self.invoice.balance self.invoice.update_attributes(balance: current_balance - self.amount) end end </code></pre> <p>Another way that you may try will be to use <code>accepts_nested_attributes_for</code> in your <code>Invoice</code> model:</p> <pre><code>class Invoice &lt; ActiveRecord::Base belongs_to :customer, :inverse_of =&gt; :invoices attr_accessible :payments_attributes, :due_date, :invoice_date, :reading_ids, :customer_id, :customer, :status, :amount, :balance has_many :invoice_items, :dependent =&gt; :destroy has_many :payments, :dependent =&gt; :destroy accepts_nested_attributes_for :payments end </code></pre> <p>In this case, you will be creating payments from <code>invoces#edit</code> page and you can construct your form this way: you will have "Pay Now" button that will inject <code>payments/_new_form</code> into <code>invoices/_edit_form</code>, then any time the user will enter a value into <code>amount</code> field of <code>payments/_new_form</code>, you will update the value of balance field of <code>invoices/_edit_form</code> with the value from <code>amount</code> field of <code>payments/_new_form</code> using JavaScript. Submitting <code>invoices/_edit_form</code> will save both objects. If you take this approach, check out <a href="https://github.com/ryanb/nested_form" rel="nofollow">nested_form gem</a>, it makes things easier. However, I still reccommend the callback approach, since it guarantees that invoice balance is updated <em>every time</em> (even if you do it from the console, not UI).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload