Note that there are some explanatory texts on larger screens.

plurals
  1. PORails nested form, calulate value from nested items during
    primarykey
    data
    text
    <p>I am new to rails and am working on one of my first rails projects, it is an invoice app with nested line items within the invoice form. I want to calculate the total invoice before I save the invoice. I get it to save nicely if just added items during the save process, but it doesn't calulate the total correctly if one of the nested line items is tagged to be deleted. I would have to go back in and save again to get the correct total billed amount.</p> <pre><code>class Invoice &lt; ActiveRecord::Base attr_accessible :job_name, :items_attributes, :tax1, :tax2, :subtotal before_save :calculate_totals has_many :items, :dependent =&gt; :destroy accepts_nested_attributes_for :items, allow_destroy: true private def calculate_totals self.subtotal = 0 self.items.each do |i| self.subtotal = self.subtotal + (i.quantity * i.cost_per) end end end </code></pre> <p>I'm note sure how this differs from params but the problem item record is listed in the requested paramaters with :_destroy = true</p> <pre><code>{"utf8"=&gt;"✓", "_method"=&gt;"put", "authenticity_token"=&gt;"+OqRa7vRa1CKPMCdBrjhvU6jzMH1zQ=", "invoice"=&gt;{"client_id"=&gt;"1", "job_name"=&gt;"dsdsadsad", "items_attributes"=&gt;{"0"=&gt;{"name"=&gt;"jhksadhshdkjhkjdh", "quantity"=&gt;"1", "cost_per"=&gt;"50.0", "id"=&gt;"21", "_destroy"=&gt;"false"}, "1"=&gt;{"name"=&gt;"delete this one", "quantity"=&gt;"1", "cost_per"=&gt;"10.0", "id"=&gt;"24", "_destroy"=&gt;"true"}}}, "commit"=&gt;"Update Invoice", "id"=&gt;"8"} </code></pre> <p>Thanks for you help.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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