views:

34

answers:

2

I can't find very good intros to specific callbacks in rails.

Basically I'm dealing with two models:

  1. Order
  2. Item, (nested in Order form)

I'm using the before_update model to do some basic math:

 class Order < ActiveRecord::Base
        accepts_nested_attributes_for :line_items
        before_update :do_math
protected
def do_math
  self.req_total = self.line_items.sum(:total_price)
end

req_total is the total value of the order, when a user updates the amounts I need to add up the total_price of the line_items. What am I doing wrong? My logic fails to read the newly submitted total_price.

Thanks!

A: 

Not sure about your use of sum - looks like your trying to use SQL when talking Ruby!

Try http://stackoverflow.com/questions/1538789/how-to-sum-array-members-in-ruby

Hope that helps :)

Paul Groves
A: 

Look at your log. The sum method does a SQL sum from the database. In that case, it may not be working since the child model (line_items) members may not have been saved to the db yet.

As an alternative, try

self.req_total = 0
line_items.each{|item|self.req_total += item.total_price}   

ps. The sum method for ActiveRecord associations is not the same sum method as for enumerables, regular arrays, etc. The ActiveRecord sum method is really the calculate(:sum) method.

Larry K