Calculate parent and child totals

5

Friends I have 2 models. Orders have several details. I use cocoon to create the forms. The order model has a total that is the sum of the totals of the child models. What I would like to know is how best to implement a sum in the child and then in the parent of the total field and quantity whenever the template is saved.

order template fields:

t.string   "customer_id"
t.decimal  "valor_total"
t.integer  "item_total"
t.string   "order_num"
t.datetime "created_at"
t.datetime "updated_at"

template detail fields:

t.string   "order_id"
t.string   "cod_produto"
t.string   "desc_produto"
t.string   "cod_cor"
t.string   "desc_cor"
t.string   "desc_tamanho"
t.decimal  "preco"
t.integer  "quantidade"
t.datetime "created_at"
t.datetime "updated_at"
t.float    "total"

order.rb

class Order < ActiveRecord::Base
   has_many :details, dependent: :destroy
   belongs_to :customer
   accepts_nested_attributes_for :details, :reject_if => :all_blank, :allow_destroy => true
   validates :customer_id,
             :presence => true
end

detail.rb

class Detail < ActiveRecord::Base
   belongs_to :order
end
    
asked by anonymous 23.02.2016 / 22:32

3 answers

2

Personal problem solved. The templates look like this:

class Order < ActiveRecord::Base
has_many :details, dependent: :destroy
belongs_to :customer
accepts_nested_attributes_for :details, :reject_if => :all_blank, :allow_destroy => true
validates :customer_id,
        :presence => true
before_save :sum_details
private
  def sum_details
   self.valor_total = self.details.inject(0){|sum,detail| sum +   detail.total }
  end
end

class Detail < ActiveRecord::Base
belongs_to :order
before_save :sum_prices
   private
   def sum_prices
     self.total = self.preco*self.quantidade 
   end
end

Thank you all!

    
24.02.2016 / 18:50
0

Do the following, in the detail.rb template, leave it like this:

class Detail < ActiveRecord::Base
   belongs_to :order
   before_save :sum_prices

   private 
   def sum_prices
     self.total = self.preco*self.quantidade
     self.save!
   end

end

In order.rb, leave this:

class Order < ActiveRecord::Base
   has_many :details, dependent: :destroy
   belongs_to :customer
   accepts_nested_attributes_for :details, :reject_if => :all_blank, :allow_destroy => true
   validates :customer_id,
             :presence => true
   before_save :sum_details


   private
   def sum_details
     total = 0
     self.details each do |d|
      total += d.total
     end
     self.valor_total = total
     self.save!
   end
end
    
23.02.2016 / 22:56
0

You can make the sum_details method a bit more concise.

def sum_detail
  self.valor_total = self.details.inject(0){|sum,detail| sum + detail.total }
end

Remove self.save! of sum_prices and sum_details.

    
23.02.2016 / 23:04